0

Suppose I have an array which contains the values

String studentList[] = {Paul, null, null};

Now I wanna add another student but make sure before if the student is not already in there.

I have already a for loop which checks if the value is null and if it is then add the student.

  • 3
    Using the same for loop that goes through all values. Check for the current value equalling the name you want to enter. If it does, then just return out of your loop and don't perform the add – benjiiiii Dec 11 '17 at 11:03
  • https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains%28java.lang.Object%29 – joao86 Dec 11 '17 at 11:04
  • Possible duplicate of [Java Array, Finding Duplicates](https://stackoverflow.com/questions/3951547/java-array-finding-duplicates) – ogtega Dec 11 '17 at 11:05

3 Answers3

4

You should use a Set, HashSet as the exact implementation and convert that to array afterwards.

Eldon Hipolito
  • 704
  • 1
  • 8
  • 24
0

Add result to a hash set

1.HashSet contains unique elements only.

    HashSet<String> studentList=new HashSet<String>();  
    studentList.add("Paul");  
Ann
  • 463
  • 5
  • 15
  • I don't know about that. I can do `studentList.put("101","paul");` and then there will be 2 pauls – Tim Dec 11 '17 at 11:12
  • 3
    Do not use concrete `HashSet` for declaration, always try to use the abstract which is `Set`. This helps a lot when you are passing different implementations. – Eldon Hipolito Dec 11 '17 at 11:25
0

You'd be better off using a Set, however, you can do this:

    String studentList[] = {"Paul", null, null};
    for (int i = 0; i < studentList.length; ++i) {
        if (studentList[i] == null) {
            studentList[i] = newStudent;
            break;
        } else if (studentList[i].equals(newStudent)) {
            break;
        }
    }
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24