toString&HashSet:
import java.util.HashSet;
class Value{
int i=10;
//int get(int i) {
//return i;
//}
public String toString() {//重点是toString函数名
return ""+i;
}
}
public class Notebook {
public static void main(String[] args) {
HashSet<Integer> word=new HashSet<Integer>();
word.add(1);
word.add(2);
word.add(3);
System.out.println(word);//直接输出对象,因为HashSet里面toString
Value c=new Value();
System.out.println(c);
}
}
HashMap:
package notebook;
import java.util.HashMap;
import java.util.Scanner;
class Notebook {
HashMap<Integer,String> word=new HashMap<Integer,String>();//HashMap<Integer数据的序号,String数据>注意不能用int
//创建一个HashMap的对象
void addword() {
//写入集合表的数据用put 括号内(int,string)
word.put(1,"蜜汁鸡");
word.put(2,"v记");
word.put(3,"肥牛卷");
System.out.println(word.keySet());//KeySet键表,也是刚才说的序号表,访问所有的序号
System.out.println(word.values());//访问集合表中所有的内容
System.out.println(word.values().size());//size 用来访问集合表中有多少有效内容
}
String getword(int i) {
//get函数 通过序号来使用集合表中的内容
System.out.println(word.containsKey(i));//containsKey(int)用来查找集合表中的序号是否有外部输入的数字,如果表中查到有则输出true 没有则输出false
System.out.println(word.containsValue("蜜汁鸡"));//与containsKey类似这个用来查找表中是否有外部输入的字符串,如果有则输出true 没有false
return word.get(i );
}
public static void main(String[] args) {
Notebook w=new Notebook();
Scanner in=new Scanner(System.in);
w.addword();//使用我们刚才填写的集合表,如果没有这行代码,集合表的内容为null
String name=w.getword(in.nextInt());
System.out.println(name);
System.out.println();
}
}
版权声明:本文为CFXLWT原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。