0

Consider a text file of IDs, with one ID per line, which has duplicate IDs. We would like to eliminate the duplicate IDs by using an ArrayList. Read each ID from the file, add it to the ArrayList if it is not already added, and then output all IDs in the ArrayList to a new text file..

i solved it that i will add all the id and then cheek if they exist and remove them however my doctor did not want them to be add in the first place

 ArrayList<Integer> myid = new ArrayList<Integer>();

     int idset,count=14;

     while(sc.hasNextInt()) {
         idset = sc.nextInt();
         myid.add(idset);
     }
     for (int i = 1; i < myid.size(); i++) {
         int a1 = (int) myid.get(i);
         int a2 = (int) myid.get(i-1);
         if (a1 != a2) {
             count--;
         }
             else {
                 myid.remove(a1);
             }
     }
     pw.println(myid);
     pw.println("duplicate = "+count);
6
  • 7
    ehm ... ok? usually, my doctor just tells me whether I'm healthy or not. That being said: do you have a question? Commented Mar 11, 2020 at 7:55
  • 1
    use a Set - docs.oracle.com/javase/7/docs/api/java/util/Set.html. Example: baeldung.com/convert-list-to-set-and-set-to-list Commented Mar 11, 2020 at 7:58
  • 2
    Yep, Just use a Set instead and tell your Doctor to chill. Commented Mar 11, 2020 at 7:59
  • 1
    Did you mean: professor? Commented Mar 11, 2020 at 8:15
  • sorry its normal in my native langue to call professor doctor Commented Mar 11, 2020 at 8:35

2 Answers 2

1

So, the requirements didn't ask you to count anything... Not sure where count=14 comes from.

did not want them to be add in the first place

Then don't add them

Use List#contains

while (sc.hasNextInt()) {
     idset = sc.nextInt();
     if (!myid.contains(idset)) { // <--- here
         myid.add(idset);
     }
 }
 myid.foreach(pw::println);

Note: The above code has O(n^2) runtime complexity, and Set<Integer> is more appropriate for this question, which has a runtime of O(n), for the set of n ids.

And you could just make new ArrayList<>(set) to return a list, if you really wanted one

Sign up to request clarification or add additional context in comments.

Comments

0
while(sc.hasNextInt()) {
    idset = sc.nextInt();
    if (!myid.contains(id)) {
        myid.add(idset);
    }
}

use the ArrayList.contains method

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.