一、HashSet
基于 HashMap 来实现的,是一个不允许有重复元素的集合。
HashSet 允许有 null 值。
HashSet 是无序的,即不会记录插入的顺序。
import java.util.HashSet;
public class MySet {
public static void main(String[] args) {
HashSet<String> sites = new HashSet<String>();
sites.add("1aobao");
sites.add("Google");
sites.add("Runoob");
//sites.add("Taobao");
sites.add("Zhihu");
// sites.add("Runoob"); // 重复的元素不会被添加
for (String i : sites) {
System.out.println(i);
}
}
}
二、HashMap
是一个散列表,它存储的内容是键值对(key-value)映射。
HashMap 实现了 Map 接口,根据键的 HashCode 值存储数据,具有很快的访问速度,最多允许一条记录的键为 null,不支持线程同步。
HashMap 是无序的,即不会记录插入的顺序。
import java.util.HashMap;
public class MyMap {
public static void main(String[] args)
{
HashMap<Integer, String> Sites = new HashMap<Integer, String>();
// 添加键值对
Sites.put(1, "Google");
Sites.put(2, "Runoob");
Sites.put(3, "Taobao");
Sites.put(4, "Zhihu");
Sites.remove(4);
for(String v:Sites.values())
System.out.print(v+",");
System.out.println(Sites);
}
}
三、Java 泛型
java 中泛型标记符:
- E - Element (在集合中使用,因为集合中存放的是元素)
- T - Type(Java 类)
- K - Key(键)
- V - Value(值)
- N - Number(数值类型)
下面的例子遇到的问题是:把Double用成了double,结果报错:Double [] doua= {1.1,1.2,1.3,1.4,1.5,1.6}; 错误敲成:double [] doua= {1.1,1.2,1.3,1.4,1.5,1.6};。此处要理解并注意。
演示了如何使用泛型方法打印不同类型的数组元素:
public class GenericMethodTest {
public static <E> void printArray(E[] inputArray)
{
for(E element: inputArray)
{
System.out.printf("%s",element);
}
System.out.println();
}
public static void main(String[] args)
{
Integer [] inta= {1,2,3,4,5,6};
Double [] doua= {1.1,1.2,1.3,1.4,1.5,1.6};
Character [] cha= {'a','b','c'};
System.out.println( "整型数组元素为:" );
printArray( inta ); // 传递一个整型数组
System.out.println( "\n双精度型数组元素为:" );
printArray(doua); // 传递一个双精度型数组
System.out.println( "\n字符型数组元素为:" );
printArray( cha ); // 传递一个字符型数组
}
}
2.泛型----实例
下面的例子演示了"extends"如何使用在一般意义上的意思"extends"(类)或者"implements"(接口)。该例子中的泛型方法返回三个可比较对象的最大值。
public class FanXingTest {
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max=x;
if(y.compareTo(max)>0) max=y;
if(z.compareTo(max)>0) max=z;
return max;
}
public static void main(String[] args)
{
System.out.printf("%d, %d 和 %d 中最大的数为 %d\n\n", 3, 4, 5, maximum(3, 4, 5));
System.out.printf("%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
System.out.printf("%s, %s 和 %s 中最大的数为 %s\n", "pear", "apple", "orange", maximum( "pear", "apple", "orange" ) );
}
}