开发者

how to automatically rename object in java

开发者 https://www.devze.com 2023-04-13 01:51 出处:网络
I have list of String. List<String> elements= new ArrayList<String>(); when I wanna add new String

I have list of String. List<String> elements= new ArrayList<String>(); when I wanna add new String

elements.add("element");

with name which is my arraylist I wanna to automatically rename to _[a-z...] as windows rename file when there are two same... so for example I have in arrayl开发者_如何学Cist "element" when I add element again I wanna to rename automatically to element_a ... so

    if (elements.contains("element")) { 
    something
}

is there some function in java ? thx for help


Well you can make your own list that extends ArrayList, overwrite the add(...) method and first check if the string is already present in the list (super.contains(...)) then rename it if necessary and then add it as usual (super.add(...)).


No built-in function, but it's not too hard. For example:

public static void main(String[] args) {
    List<String> l = new ArrayList<String>();
    add("foo", l);
    add("foo", l);
    add("foo", l);
    add("foo", l);
    add("foo", l);
    add("foo", l);
    add("foo", l);
    add("foo", l);
    System.out.println(l);
}

static void add(String element, List<String> elements) {
    if (elements.contains(element)) {
        elements.add(nextValudFor(element, elements));
    } else {
        elements.add(element);
    }
}

static String nextValudFor(String element, List<String> elements) {
    for (char c = 'a'; c <= 'z'; c++) {
        String next = element + '_' + c;
        if (!elements.contains(next)) {
            return next;
        }
    }
    throw new IllegalStateException("Ran out of letters!");
}

Outputs:

[foo, foo_a, foo_b, foo_c, foo_d, foo_e, foo_f, foo_g]

For best effect, you'd probably want to wrap this up into your own List type as appropriate.

0

精彩评论

暂无评论...
验证码 换一张
取 消