Java: Array 的操作练习

/**
 * 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);


}
}

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值