newcoder1010 3 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 Quote Link to post Share on other sites
Makwana Prahlad 1 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; } Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.