java陣列:去重,增加,刪除元素
阿新 • • 發佈:2018-12-14
java陣列:去重,增加,刪除元素
import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; public class Code { public static void main(String [] args) { testA(); System.out.println("==========================="); testB(); System.out.println("==========================="); testC(); } //去掉陣列中重複的值 public static void testA() { String [] str = {"Java", "C++", "Php", "C#", "Python", "C++", "Java"}; for (String elementA:str ) { System.out.print(elementA + " "); } List<String> list = new ArrayList<String>(); for (int i=0; i<str.length; i++) { if(!list.contains(str[i])) { list.add(str[i]); } } String[] newStr = list.toArray(new String[1]); //返回一個包含所有物件的指定型別的陣列 for (String elementB:newStr ) { System.out.print(elementB + " "); } System.out.println(); } //刪除陣列中其中一個元素 public static void testB() { String [] str = {"Java", "C++", "Php", "C#", "Python"};//刪除php List<String> list = new ArrayList<String>(); for (int i=0; i<str.length; i++) { list.add(str[i]); } list.remove(2); //list.remove("Php") String[] newStr = list.toArray(new String[1]); //返回一個包含所有物件的指定型別的陣列 } //在陣列中增加一個元素 public static void testC() { String [] str = {"Java", "C++", "Php", "C#", "Python"};//增加ruby List<String> list = new ArrayList<String>(); for (int i=0; i<str.length; i++) { list.add(str[i]); } list.add(2, "ruby"); String[] newStr = list.toArray(new String[1]); //返回一個包含所有物件的指定型別的陣列 } }
定義一個型別的二維陣列 String[][] a;
定義一維陣列長度 a = new String[i][];
定義二維陣列長度 a[i] = new String[j]
例子:將一個字串的內容分隔,並且放入一個二維陣列中
public class TestToString { public static void main(String[] args) { String s = "0,1;3,6,4;7,1"; String[] a = s.split(";"); double[][] d; d = new double[a.length][]; for(int i=0; i<a.length; i++){ String[] s_num = a[i].split(","); for(int j=0; j<s_num.length; j++){ d[i] = new double[s_num.length]; d[i][j] = Double.parseDouble(s_num[j]); System.out.println("d[" + i + "][" + j +"] = " + d[i][j]); } } }
堅持不懈