Java delete array elements and delete duplicate array elements of the code

  • 2020-04-01 02:19:44
  • OfStack

Delete the array by list


private String[] removePaths(String path, String[] srcpaths) {
  List<String> list = new ArrayList<String>();
  int k = srcpaths.length;//Original string length
  int i=0;
  while(i<k){
   if(!srcpaths[i].equals(path)){
    list.add(srcpaths[i]);                      //Add to the list without waiting
   }
   i++;
  }
  String[] temp = new String[list.size()];
  for(int j=0;j<list.size();j++){
   temp[j] = list.get(j);
  }
  return temp;
}

No compiler, just write whatever you want, that's probably what it means...


private String[] removePaths(String path, String[] srcpaths) {
    List list = Arrays.asList(srcpaths);
    list.remove(path);
    String[] temp = new String[list.size()];
    return list.toArray(temp); 
}

Deletes the same element from the array

Start by sorting the source array by default

Make the same element adjacent

Then loop to delete the same element

 
<html>
<body>
<script type="text/javascript">
var source = [" Lin "," lu "," Dai zhong "," Lin "," When moving "," Zhu Gui "];
var target = new Array();
source.sort();
target.push(source[0]);
for(var i=1;i<source.length;i++)
{
if(source[i] != source[i-1])
{
target.push(source[i]);
}
}
document.write(' The original array: ' + source + "<br />");
document.write(' Required array: ' + target);
</script>
</body>
</html>

Add two more instances


    public static void main(String[] args) { 
    getDistinct(new int[] { 6, 7, 3, 6, 5, 2, 7, 8 }); 
    } 
    static void getDistinct(int array[]) { 
    java.util.List list = new java.util.ArrayList(); 
    for (int i = 0; i < array.length; i++) { 
    if (!list.contains(array[i])) { 
    list.add(array[i]); 
    System.out.print(array[i] + " "); 
    } 
    } 
    } 

      Output: 6, 7, 3, 5, 2, 8 

Take a look at the contains() method of the ArrayList source code:

 
    public boolean contains(Object elem) { 
    return indexOf(elem) >= 0; 
    } 
    public int indexOf(Object elem) { 
    if (elem == null) { 
    for (int i = 0; i < size; i++) 
    if (elementData[i]==null) 
    return i; 
    } else { 
    for (int i = 0; i < size; i++) 
    if (elem.equals(elementData[i])) 
    return i; 
    } 
    return -1; 
    } 


Related articles: