newcoder1010 Posted July 8, 2020 Report Share Posted July 8, 2020 (edited) Hello, I am trying to do a task. I have a list of people’s names “John”,”Mike”,”Sam”. How can I remove all the names named “Mike”? Can you please help me? I am getting few errors in the below code: package QA1; import java.awt.List; import java.util.ArrayList; import java.util.Scanner; public class JavaRemoveNameArray { String[] myStrArray = {"John","Mike","Sam"}; System.out.println("Before: "+Arrays.toString(myStrArray)); List<String> myList = new ArrayList<String>(Arrays.asList(myStrArray)); myList.remove("Mike"); myStrArray = myList.toArray(new String[0]); System.out.println("After: "+Arrays.toString(myStrArray)); } Thanks! Edited July 8, 2020 by newcoder1010 Link to comment Share on other sites More sharing options...
Makwana Prahlad Posted July 13, 2020 Report Share Posted July 13, 2020 public static Object[] remove(Object[] array, Object element) { if (array.length > 0) { int index = -1; for (int i = 0; i < array.length; i++) { if (array[i].equals(element)) { index = i; break; } } if (index >= 0) { Object[] copy = (Object[]) Array.newInstance(array.getClass() .getComponentType(), array.length - 1); if (copy.length > 0) { System.arraycopy(array, 0, copy, 0, index); System.arraycopy(array, index + 1, copy, index, copy.length - index); } return copy; } } return array; } Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now