1

I have an array like below:

PersonClass[] person= {
            new PersonClass("90234234434", "John", "Smith", 22, "Street 22/5", 10//this is priority from 0 up to 10),
            ...
            ...
    };

Then I search for a security ID that starts from 98

for(int n = 0; n < person.length; n++)
    {
        if(person[n].getSecId().contains("98"))
        {
            System.out.println(person[n].toString());s
            //delete this object from person array
        }
    }

Now my question is: Can I delete this object directly from the array, if not how can I convert it into collection eg. ArrayList.

tushar_lokare
  • 461
  • 1
  • 8
  • 22
G. Dawid
  • 162
  • 1
  • 11
  • Set it to `null`. GC will delete it by itself. – Some Name Feb 10 '19 at 11:29
  • duplicate https://stackoverflow.com/questions/642897/removing-an-element-from-an-array-java – Ruslan Feb 10 '19 at 11:30
  • 2
    Possible duplicate of [How do I remove objects from an array in Java?](https://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) – Tristan Feb 10 '19 at 11:30
  • by the way.. if you want to check if ID starts with 98 you should use `startsWith()` method – Ruslan Feb 10 '19 at 11:33
  • A remark: If you want to delete `Person`s which `secId`s start with, some string, use [`String#startsWith(...)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#startsWith(java.lang.String)) instead of [`String#contains(...)`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#contains(java.lang.CharSequence)). – Turing85 Feb 10 '19 at 11:38
  • Every other post on stackoverflow didn't solve my problem. I want to delete it straight from array, not from collections. – G. Dawid Feb 10 '19 at 11:40

2 Answers2

2

If you are using Java 8 you can use :

person = Arrays.stream(person)
           .filter(p -> !p.getSecId().startsWith("98")) // note the not ! here
           .toArray(PersonClass[]::new);

Another thing :

Then I search for security ID that starts from 98

in this case you can replace contains with startsWith to just check the first characters.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

You could use the static method java.util.Arrays.asList() to covert an array into an ArrayList

willi b.
  • 1
  • 1
  • 1
  • 1
    This is poorly documented, but the List returned by Arrays.asList() does not support structural (add or remove) operations. It and its iterator only support replacing existing elements. – Matthew Leidholm Feb 11 '19 at 14:24