import java.util.*;
public class SetTest {
public static void main(String[] args){
Set<String> words = new HashSet<>();
long totalTime = 0;
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String word = in.next();
long callTime= System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis() - callTime;
totalTime += callTime;
}
Iterator<String> iter =words.iterator();
for(int i= 0 ; i != 20 && iter.hasNext(); i++)
System.out.println(iter.next());
System.out.println("...");
System.out.println(words.size() + " distinct words "+totalTime + "milliseconds.");
}
}
學(xué)習(xí)HashSet的結(jié)構(gòu),在書中看到的代碼
然后 按照書中的運(yùn)行 java SetTest > alice30.txt
運(yùn)行失敗,提示沒有運(yùn)行成功,所以查資料,發(fā)現(xiàn)是java的環(huán)境沒有搭好
解決的網(wǎng)站
按照這里搭建成功
途中學(xué)習(xí)到Run AS configurations的arguments可以添加main的輸入
在指定文件夾點(diǎn)擊shift,可以打開讓命令行直接進(jìn)入該文件夾
代碼中的知識點(diǎn)
1.Scanner類
java.util.Scanner 是 Java5 的新特征椒袍,我們可以通過 Scanner 類來獲取用戶的輸入瘾晃。
使用
Scanner s = new Scanner(System.in);
Scanner 類的 next() 與 nextLine() 方法獲取 輸入的字符串遇绞,在讀取前我們一般需要 使用 hasNext 與 hasNextLine 判斷是否還有輸入的數(shù)據(jù):
next 和 nextLine
next是省略空格,讀取字符(類似c++的cin>>)
nextLine是讀取行如果要輸入 int 或 float 類型的數(shù)據(jù)惭适,在 Scanner 類中也有支持,但是在輸入之前最好先使用 hasNextXxx() 方法進(jìn)行驗(yàn)證,再使用 nextXxx() 來讀取:
demo
2.HashSet
1.是一個(gè)保存元素的容器,但是不允許有相同個(gè)元素,插入,刪除效率高
定義
Set<String> names = Hash<>();
添加元素
name.add("yhq");
使用迭代器遍歷
Iterator iter = name.iterator();
while(iter.hasNext){
System.out.println(iter.next());
}