惨淡经营

想不被别人淘汰,先得学会自己淘汰自己!

导航

java学习

Java does not have explicit pointers; in a sense, all variables that refer to objects are pointers. When you assign between two objects of the same type, you actually assign a reference to the object on the right-hand side. To create a new instance of an object, you need to call one of its constructors:

myObject a, b;

= b;                 // reference

= new myObject(b);   // create a new object

In Java, the + operator can concatenate strings together. A sequence such as the following

String greeting = "Hello";
greeting 
= greeting + " there";

 is legal. Because the original String that greeting points to cannot be modified, the concatenation actually involves the creation of a new String, which greeting is then set to point to. Therefore, the reference to the original "Hello" string is removed, which eventually causes it to be destroyed.
The concatenation statement also involves some more behind-the-scenes magic by the compiler. It creates a temporary StringBuffer, then calls the StringBuffer.append() method for each expression separated by a + sign, then calls StringBuffer.toString() to convert it back to the result String. As with the automatic creation of String objects from constant strings, this is a special case on the part of Java, but is there because string concatenation is so useful.

Arrays can also hold objects, so you can declare the following:

MyObject[] objarray;

This would then be created as follows (this could be combined with the declaration):
objarray = new MyObject[5];
It is important to note that this creates only the array. You still need to create the five objects:
for (k = 0; k < 5; k++{

    objarray[k] 
= new MyObject();

}


To create subarrays, create an array where each element is an array. The first array can be declared and created in one step

int[][] bigArray = new int[6][];
and then each subarray needs to be created (each one can be a different length, in fact):
for (m = 0; m < 6; m++{

    bigArray[m] 
= new int[20];

}

You can initialize arrays when they are declared:

short[][] shortArray = 123 },  4 },  5 , 6 } };


After that, shortArray[0] would be an array of three elements,
shortArray[1] would be an array of one element,
and shortArray[2] would be an array of two elements.

posted on 2007-04-05 15:15  hone  阅读(279)  评论(0编辑  收藏  举报