Comparing Strings using ArrayList [closed]

1

I need to repeat the same string, I know that I need to use .equals (), but it is giving error, as if the variable x was checking more value than exists in the ArrayList, but has as condition that x is smaller that the "data.size ()" (which is the size of my vector).

public static void main(String args[]) {
        ArrayList<String> dados= new ArrayList<String>();

        //OBS. Primeiramente inserir os dados, futuramente
        //ler arquivos txt
        dados.add("Dado 2");
        dados.add("Dado 1");
        dados.add("Dado 3");
        dados.add("Dado 3");
        dados.add("Dado 3");
        Collections.sort(dados);  
        //while(dados.contains(dados)){
          //  System.out.println("deu certo");
        //}       
        //for (String x : dados){
        //    System.out.println(x);
        //    if (x.contains(x))
       // }     
        int i;
        int contador = 0;
        int x = 0;
        int tamanho = dados.size();
        for (i = 0; i<tamanho; i++){        
            System.out.println(dados.get(i));
                if (x<dados.size() && dados.get(i).equals(dados.get(++x))){
                System.out.println("entrou no contador");
                contador++;
                }              
        } 
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new main().setVisible(true);
            }
        });
    }

Error generated from code:

[ERRO]run:Dado1Dado2Exceptioninthread"main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
Dado 3
entrou no contador
Dado 3
entrou no contador
Dado 3
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at projetoic.main.main(main.java:118)
C:\Users\lsilv\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
FALHA NA CONSTRUÇÃO (tempo total: 5 segundos)
    
asked by anonymous 29.08.2017 / 18:29

4 answers

0

The problem is here:

  

dados.get(++x)

++x is different from x++ :

  • Post Increment ( x++ ): The post increment happens after the current expression ends. For example, assuming that x = 1 , if you do dados.get(x++) you will have the index item 1 and after that item is returned (or better, after the entire expression is finished), then x receives an increment and becomes 2 . Briefly, in literal terms what happens is: dados.get(1)

  • Pre Increment ( ++x ): Pre increment happens before the expression exits. For example, assuming that x = 1 , if you do dados.get(++x) first the variable x will receive an increment, changing its value to 2 and only then will the previous expression continue, causing you to get index 2 of the list, not the 1 . Briefly, in literal terms what happens is: dados.get(2) .

That way, even if you validate on if , when you use the operator as a pre-increment, you'll try to search for a nonexistent position in your list.

Switch to dados.get(x++) and it will work.

    
30.08.2017 / 03:29
3

You can use java Streams to count as follows:

List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");

Map<String, Long> counted = list.stream()
   .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

The above code makes a stream and groups the words e -> e and counting the occurrences Collectors.counting() . This way the resulting map is < Word, Events >

The result is as follows:

{a=4, b=2, c=2, d=1}

See ideone

As for your code is as they have already spoken, pay attention to the condition of the loop. (It's i

29.08.2017 / 19:14
2

1 - The index i goes from 0 to size-1: data [0] == "Data 1" ... data [4]="Data 3" (the last Data 3). Therefore the for condition must be 'i < size '.

2 - The condition 'x

29.08.2017 / 19:10
2

You are trying to access index 5 from an array that goes up to 4 (0,1,2,3,4).

    
29.08.2017 / 21:44