1

I have an array of files names ending with either .xml or .gxml. I am putting each element into another array. I need to ensure that the same file name is not added twice.

So the real question is how do I ensure the same element is not added twice into an array?

4 Answers 4

9

Use Set instead of array for processing, to ensure it doesn't appear twice

Set<String> fileNames = new HashSet<String>();
fileNames.add("1.txt");
fileNames.add("2.txt");
// not necessarily in that order with HashSet
System.out.println(fileNames); //[1.txt,2.txt]
fileNames.add("1.txt");// it will not add this one
System.out.println(fileNames); //[1.txt,2.txt]
Sign up to request clarification or add additional context in comments.

Comments

1

Loop through the array each time you add the item, and compare the two. If they are the same, don't add the new one.

    for (int i = 0; i < array.length; i++)

    if (object = array[i]) {
       //DONT ADD THE OBJECT HERE
    else {
        //add the object
    }

}

Comments

0

Using a set is the best option. Another way can be to use a HashMap with file name as key and file object as value.

HashMap<String,File> fileMap = new HashMap<String,File> ();

if (fileMap.get("fileName")==null)
fileMap.put("fileName",file)

Comments

0

In Kotlin :-

fun singleNumber(nums: IntArray): Int {
        val set=hashSetOf<Int>()
        for(x in nums){
            if(set.contains(x)){
                set.remove(x)
            }else{
                set.add(x)
            }
        }
        return set.first()
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.