To delete array elements and filter repeated array elements in java, We need to traverse the array and then remove the Array Based on the value or method we set. I will introduce it to you one by one.
Delete an array by means of list
| The Code is as follows: |
Copy code |
|
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]); // you can add it 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 it. That's what it means...
| The Code is as follows: |
Copy code |
|
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 );
} |
Delete the same element from the array
Sort the source array by default.
Adjacent identical elements
Then, perform a circular operation to delete the same element.
| The Code is as follows: |
Copy code |
|
<Html>
<Body>
<Script type = "text/javascript">
Var source = ["Lin Chong", "Lu zhishen", "Dai Zong", "Lin Chong", "Shi Qian", "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 ('original array: '+ source + "<br/> ");
Document. write ('required array: '+ target );
</Script>
</Body>
</Html> |
Add two more instances.
| The Code is as follows: |
Copy code |
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 ArrayList contains () method source code:
| The Code is as follows: |
Copy 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;
}
|