编译器抱怨这段代码:
HashMap<String,int> userName2ind = new HashMap<String,int>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
Run Code Online (Sandbox Code Playgroud)
它写出"意外类型"并指出int.如果我替换intby String和i+1by i+"1",编译就可以了.这里有什么问题?
在非常抽象的层面上,我知道包装类,创建原始数据类型的对象,但我很好奇为什么我们需要使用包装类以及它们对原始数据类型提供了什么好处.
考虑Java中的以下两段代码,
Integer x=new Integer(100);
Integer y=x;
Integer z=x;
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
Run Code Online (Sandbox Code Playgroud)
在我的系统上测试时的内存使用情况:使用的内存(字节):287848
和
int a=100;
int b=a;
int c=a;
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
Run Code Online (Sandbox Code Playgroud)
在我的系统上测试时的内存使用情况:使用的内存(字节):287872
和以下
Integer x=new Integer(100);
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
Run Code Online (Sandbox Code Playgroud)
和
int a=100;
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
Run Code Online (Sandbox Code Playgroud)
在上述两种情况下,在我的系统上测试时内存使用情况完全相同:使用的内存(字节):287872
该声明
System.out.println("Used memory (bytes): " +
(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
Run Code Online (Sandbox Code Playgroud)
将显示当前正在使用的总内存[可用内存总量 - 当前可用内存],(以字节为单位).
我已经通过上述方法验证了在第一种情况下,内存使用(287848)低于第二种(287872),而在其余两种情况下,它完全相同(287872).当然,显然,它应该是这样的,因为在第一种情况下,y和z包含x中保存的引用的副本,并且它们的所有(x,y和z)指向相同/共同的对象(位置)意味着第一种情况比第二种情况更好,更合适,在这两种情况的其余情况下,存在具有完全相同的内存使用情况的等效语句(287872).如果是这样的话,那么在Java中使用原始数据类型应该是无用的并且可以避免,尽管它们基本上是为了更好的内存使用和更高的CPU利用率而设计的.为什么Java中的原始数据类型存在?
有点类似于这个问题的问题已在这里发布,但它没有这样的情况.
所以我刚开始用Java编写第二个编程类,这是教授给我们演示循环和数组的例子.
public class ArraysLoopsModulus {
public static void main(String [ ] commandlineArguments){
//Declare & Instatiate an Array of 10 integers
Integer[ ] arrayOf10Integers = new Integer[10];
//initialize the array to the powers of 2
Integer powersOf2 = new Integer(1);
for(int i=0;i<arrayOf10Integers.length;i++){
arrayOf10Integers[i] = powersOf2;
//multiply again by 2
powersOf2 = powersOf2 * 2;
}
//display the powers of 2
System.out.println("The first 10 powers of 2 are: ");
for(int i=0;i<arrayOf10Integers.length;i++){
System.out.print(arrayOf10Integers[i] + ", ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
看了所有即将到来的例子,似乎我的教授从不使用原始数据类型,他总是使用等效的对象类(在这种情况下Integer代替int …