/**
* This Class is created to practise creating and accessing Java arrays
*
* @author Oliver Zang
*
**/
import java.util.*;
public class PracArray{
public PracArray(){
System.out.println("yeah, cuz i am just that good");
}
public static void main(String[] args){
// 1.declare an array and then intialize it
Object arr[];
arr =new Object[]{1,"2",3};
//2. or you could do the declaration and intialization together
Object arrPracMember[] = {1,'T',"Oliver"};
//3. check the length of arr
int arrLength = arr.length;
//4.go through all elements
for (Object arrObject:arrPracMember){
System.out.println(arrObject);
}
//5. convert an array of ints to Strings,
//and yeah you need to import java.util.Arrays
int arrInt[] = {1,2,3,4};
String arrStrings = Arrays.toString(arrInt);
System.out.println(arrStrings);
//6. create an arraylist that only accepts String elements,
// by copying elements of arrPracMember,
//again import another package java.util.Arraylist
String arrStr[] = new String[arrPracMember.length];
int arrStrIterator = 0;
for (Object arrObject:arrPracMember){
arrStr[arrStrIterator++] = arrObject.toString();
}
ArrayList<String> aLPracMember =new ArrayList<String>(Arrays.asList(arrStr));
System.out.println("You did it! Arraylist content: "+ aLPracMember);
//7. identify if element "Oliver" exists in arrStr
String searchElement ="Oliver";
if (Arrays.asList(arrStr).contains("Oliver")){
System.out.println("Yes " + searchElement + " is here");
}
else{
System.out.println("Oops " + searchElement + " is not here");
}
//8. Convert arrStr into a set named hSetStr
// noted that a Set has no duplicated elements
//Well just import java.util.*
Set<String> hSetStr = new HashSet<String>(Arrays.asList(arrStr));
System.out.println("hSetStr content: " + hSetStr);
//9. Convert arrStr into a list named listStr
List<String> listStr = new ArrayList<String>(Arrays.asList(arrStr));
System.out.println("listStr content: " + listStr);
//10. copy content of arrStr to arrStrCopy
String arrStrCopy[] = Arrays.copyOf(arrStr,arrStr.length);
System.out.println("Copied content: "+ Arrays.toString(arrStrCopy));
//11. compare arrStr with arrStrCopy in terms of size and each elements
System.out.println(Arrays.equals(arrStr,arrStrCopy));
//12. create an array of Strings named arrStr12 that contains identical
//elements, and then copy it to a Set as to perform duplicate removal
String arrStr12[] = {"Oliver","Kimiko","MerryWeather","Duplicate","Duplicate"};
Set<String> setStr12 = new HashSet<String>(Arrays.asList(arrStr12));
System.out.println(setStr12);
}
}
输出结果: