此方法向字符串[]添加一个字符串,排除所有重复项。
/*from n o w j a v a . c o m*/ //package com.nowjava; public class Main { public static void main(String[] argv) throws Exception { String s1 = "nowjava.com"; String[] arr = new String[] { "1", "abc", "level", null, "nowjava.com", "asdf 123" }; System.out.println(java.util.Arrays.toString(addToArray(s1, arr))); } /** * This method adds a String to a String[] excluding all duplicates. * @param s1 * @param arr * @return String[] */ private static String[] addToArray(String s1, String[] arr) { //Checks for duplicates ignoring case// 来自 时代Java if (duplicateInsertion(s1, arr) == true) return arr; //Increase array size by 1 String[] tempList = arr.clone(); arr = new String[arr.length + 1]; //Add in original elements if (!(tempList.length < 1)) { for (int i = 0; i < tempList.length; i++) arr[i] = tempList[i]; } //Add new String to Array arr[tempList.length] = s1; return arr; } /** * Uses binary searching to check if a String is already in a String[]. * Upper and lower case words that are the same are considered duplicates. * ie Hat and hat are duplicates. * @param s1 * @param arr * @return */