![](/img/trans.png)
[英]Weird output is showing in console,trying to login through java in site
[英]Java code using Set showing weird output?
根據我的邏輯,以下代碼的輸出應為1。 但顯示為100。 誰能解釋我的問題在哪里?
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Set<Short> s=new HashSet<Short>();
for(Short i=0;i<100;i++){
s.add(i);
s.remove(i-1);
}
System.out.println(s.size());
}
}
答案在於裝箱和自動裝箱:
語句i-1的類型為int
而不是Short
類型。 方法remove()
接受類型為Object
的參數(不一定是集合的Generic類型)。 Java會將數字值自動裝箱為整數。 在集合中找不到整數,因此不會將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.