如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
public class lzwCode {
public static void main(String [] args) {
testA();
System.out.println( "===========================" );
testB();
System.out.println( "===========================" );
testC();
}
//去掉数组中重复的值
public static void testA() {
String [] str = { "Java" , "C++" , "Php" , "C#" , "Python" , "C++" , "Java" };
for (String elementA:str ) {
System.out.print(elementA + " " );
}
List<String> list = new ArrayList<String>();
for (int i=0; i<str.length; i++) {
if (!list.contains(str[i])) {
list.add(str[i]);
}
}
/*
Set<String> set = new HashSet<String>();
for (int i=0; i<str.length; i++) {
set.add(str[i]);
}
String[] newStr = set.toArray(new String[1]);
*/
System.out.println();
String[] newStr = list.toArray( new String[1]); //返回一个包含所有对象的指定类型的数组
for (String elementB:newStr ) {
System.out.print(elementB + " " );
}
System.out.println();
}
//删除数组中其中一个元素
public static void testB() {
String [] str = { "Java" , "C++" , "Php" , "C#" , "Python" };
for (String elementA:str ) {
System.out.print(elementA + " " );
}
//删除php
List<String> list = new ArrayList<String>();
for (int i=0; i<str.length; i++) {
list.add(str[i]);
}
list.remove(2); //list.remove("Php")
System.out.println();
String[] newStr = list.toArray( new String[1]); //返回一个包含所有对象的指定类型的数组
for (String elementB:newStr ) {
System.out.print(elementB + " " );
}
System.out.println();
}
//在数组中增加一个元素
public static void testC() {
String [] str = { "Java" , "C++" , "Php" , "C#" , "Python" };
for (String elementA:str ) {
System.out.print(elementA + " " );
}
//增加ruby
List<String> list = new ArrayList<String>();
for (int i=0; i<str.length; i++) {
list.add(str[i]);
}
list.add(2, "ruby" ); //list.add("ruby")
System.out.println();
String[] newStr = list.toArray( new String[1]); //返回一个包含所有对象的指定类型的数组
for (String elementB:newStr ) {
System.out.print(elementB + " " );
}
System.out.println();
}
}
|
控制台结果:
以上这篇Java数组,去掉重复值、增加、删除数组元素的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。