- 1
- 2
- 3
- 4
- 5
List<String> list = ...;
for (String s : someStringList)
list.add(s);
list.set(SOME_CONST, someString);
list.add(0, secondSomeString);
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+71
List<String> list = ...;
for (String s : someStringList)
list.add(s);
list.set(SOME_CONST, someString);
list.add(0, secondSomeString);
Поначалу никак не мог понять, почему list.get(SOME_CONST) != someString. Ну и копирование через цикл тоже норм
с циклом внутри не предлагать
System.arraycopy секономили чтобы скопировать десять значений, а рефлексия съела на миллион.
Я уж молчу что System.arraycopy не всегда самый эффективный способ.
>а как без цикла клонировать список?
Рефлексия, System.arraycopy? А всего-то копирующий конструктор new ArrayList(other) или как подсказывает кеп клонировать методом clone().
Чукча не знать про количество элементов, чукча отвечать. А если серьезно, как по мне, если надо часто копировать большие ArrayList'ы, может и прокатить. Достать один раз Field и поехали. Unsafe предлагать не стану - ненадежно как по мне.
>А всего-то копирующий конструктор new ArrayList(other)
Опять же только если other - ArrayList.
Да неужели?
LinkedList:
А вот и цикл. А по делу,
> как подсказывает кеп клонировать методом clone().
+1 - пусть уж имплементация решает, с циклом или без.
б) НЕ КОПИРУЙТЕ массивы System.arraycopy. используйте array.clone()
http://www.artima.com/intv/bloch13.html
Josh Bloch: If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. There are a few design flaws, the biggest of which is that the Cloneable interface does not have a clone method. And that means it simply doesn't work: making something Cloneable doesn't say anything about what you can do with it. Instead, it says something about what it can do internally. It says that if by calling super.clone repeatedly it ends up calling Object's clone method, this method will return a field copy of the original.
But it doesn't say anything about what you can do with an object that implements the Cloneable interface, which means that you can't do a polymorphic clone operation. If I have an array of Cloneable, you would think that I could run down that array and clone every element to make a deep copy of the array, but I can't. You cannot cast something to Cloneable and call the clone method, because Cloneable doesn't have a public clone method and neither does Object. If you try to cast to Cloneable and call the clone method, the compiler will say you are trying to call the protected clone method on object.
The copy constructor approach has several advantages, which I discuss in the book. One big advantage is that the copy can be made to have a different representation from the original. For example, you can copy a LinkedList into an ArrayList.
Doug Lea goes even further. He told me that he doesn't use clone anymore except to copy arrays. You should use clone to copy arrays, because that's generally the fastest way to do it. But Doug's types simply don't implement Cloneable anymore. He's given up on it. And I think that's not unreasonable.
It's a shame that Cloneable is broken, but it happens.
Который добавляет макарон в наш суп код.
Вот клоуны! Т.е. полиморфное клонирование, ради которого все это и мутили не работает?
Если бы в шарпике не проделали работу над ошибками жабы - их можно было бы смело называть долбоёбами-плагиаторами :)
Чему же?
тут клуб молодых, умных, скромных и талантливых красавчиков
проходи, налей себе чаю
Верной дорогой идете, товарищ.
Может это прозвучит для кого-то дико и удивительно, но внутри ВСЕГДА был, есть и будет цикл.
аминь
Не ну можно рекурсией. Циклы - это ж устаревшая дрянь, для придурошных императивных старпёров.
Правда нет гарантий, что внутри она не превратится jitом в ненавистный цикл!
вроде нигде не ошибся
а что вы ожидали от list.add(0, secondSomeString);?