Home > Enterprise >  I have a piece of java code but it is running error now. Hope everybody help please
I have a piece of java code but it is running error now. Hope everybody help please

Time:05-31

public static void main(String[] args) {

        List<String> list = new ArrayList<String>(Arrays.asList("20/04/2022", "20/04/2022","20/04/2022","21/04/2022", "22/04/2022", "22/04/2022"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("1000","1000","1000", "15000", "36000", "36000"));

      
        for(int i=0;i<list.size()-1;i  ) {
            while ((list.get(i).equals(list.get(i   1))) && (list2.get(i).equals(list2.get(i   1)))) {
                list.remove(i);
                list2.remove(i);
                
            }
        }
        for (String alist : list) {
            System.out.println("list1: " alist);
        }
        for (String alist2 : list2) {
            System.out.println("list2: " alist2);
        }

    }

image

image

CodePudding user response:

You need to break from the while loop, if the last item removed causes your i 1 to be out of bounds. Try this:

   for(int i=0;i<list.size()-1;i  ) {
        while ((list.get(i).equals(list.get(i   1))) && (list2.get(i).equals(list2.get(i   1)))) {
            list.remove(i);
            list2.remove(i);
            if(i 1 >= list.size() || i 1 >= list2.size()) break;
        }
   }

As gapserg has mentioned in his answer, you modify your initial list as a side effect. This would still work for your approach, but there are better alternatives.

For example, you can create a new list to copy unique pairs instead of having to delete all duplicates as stated in the comments.

Side note: Your approach only works, if the lists have the same size, if all duplicates are next to each other and if you don't care that your initial lists get modified.

CodePudding user response:

It's not idea using loop "for", because you change your "List".

List<Integer> list = new ArrayList<>(Arrays.asList(new Integer[]{1, 1, 3, 3, 3, 4, 4, 5}));
    int i = 0;
    while (i < list.size() - 1) {
        if (list.get(i).equals(list.get(i   1))) {
            list.remove(i);
        } else i  ;
    }
    System.out.println(list.toString());
  • Related