This method adds a String to a String[] excluding all duplicates. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

This method adds a String to a String[] excluding all duplicates.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s1 = "java2s.com";
        String[] arr = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        System.out.println(java.util.Arrays.toString(addToArray(s1, arr)));
    }/*  w ww  . j  a  v  a2s.c  o  m*/

    /**
     * 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
        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
     */
    private static boolean duplicateInsertion(String s1, String[] arr) {
        for (String s : arr)
            if (s1.toLowerCase().equals(s.toLowerCase()))
                return true;
        return false;
    }
}

Related Tutorials