1.不帶類型寫法:
1List listWithoutDup =
new
ArrayList(
new
HashSet(listWithDup));
2.帶類型寫法(以String類型為例):
1)Java 7以下寫法:
List<string> listWithoutDup =
new
ArrayList<string>(
new
HashSet<string>(listWithDup));</string></string></string>
2)Java 7及以上寫法:
1List<string> listWithoutDup =
new
ArrayList<>(
new
HashSet<>(listWithDup));</string>
樣例:
import
java.util.ArrayList;
import
java.util.HashSet;
import
java.util.List;
public
class
Test {
public
static
void
main(String[] args) {
List<string> listWithDup =
new
ArrayList<string>();
listWithDup.add(
"1"
);
listWithDup.add(
"2"
);
listWithDup.add(
"3"
);
listWithDup.add(
"1"
);
List<string> listWithoutDup =
new
ArrayList<string>(
new
HashSet<string>(listWithDup));
System.out.println(
"list with dup:"
+ listWithDup);
System.out.println(
"list without dup:"
+ listWithoutDup);
}
}</string></string></string></string></string>
樣例運行結果: list with dup:[1, 2, 3, 1]
list without dup:[3, 2, 1]