How do I remove repeated elements from ArrayList?

后端 未结 30 1613
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

30条回答
  •  终归单人心
    2020-11-21 06:57

    When you are filling the ArrayList, use a condition for each element. For example:

        ArrayList< Integer > al = new ArrayList< Integer >(); 
    
        // fill 1 
        for ( int i = 0; i <= 5; i++ ) 
            if ( !al.contains( i ) ) 
                al.add( i ); 
    
        // fill 2 
        for (int i = 0; i <= 10; i++ ) 
            if ( !al.contains( i ) ) 
                al.add( i ); 
    
        for( Integer i: al )
        {
            System.out.print( i + " ");     
        }
    

    We will get an array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

提交回复
热议问题