Skip to content

Instantly share code, notes, and snippets.

@gregghz
Created November 27, 2013 15:46
Show Gist options
  • Save gregghz/7677880 to your computer and use it in GitHub Desktop.
Save gregghz/7677880 to your computer and use it in GitHub Desktop.
The code here: http://graphics-geek.blogspot.com/2013/09/lazy-lists.html compared in Java and Scala.
// Java:
public class LazyListManager {
public static <T> List<T> add(List<T> list, T item) {
if (list == null) {
list = new ArrayList<T>();
list.add(item);
} else if (!list.contains(item)) {
list.add(item);
}
return list;
}
public static <T> List<T> remove(List<T> list, T item) {
if (list != null) {
list.remove(item);
if (list.isEmpty()) {
list = null;
}
}
return list;
}
}
class LazyLists {
List<Integer> intList = null;
List<Float> floatList = null;
public void addItemBetter(int item) {
intList = LazyListManager.add(intList, item);
}
public void removeItemBetter(int item) {
intList = LazyListManager.remove(intList, item);
}
public void addItemBetter(float item) {
floatList = LazyListManager.add(floatList, item);
}
public void removeItemBetter(float item) {
floatList = LazyListManager.remove(floatList, item);
}
}
// Scala:
class LazyLists {
lazy val intList: List[Int] = new ArrayList[Int]()
lazy val floatList: List[Double] = new ArrayList[Double]()
def addItemBest(item: Int): Unit = intList.add(item)
def addItemBest(item: Double): Unit = floatList.add(item)
def removeItemBest(item: Int): Unit = intList.remove(item.asInstanceOf[Object])
def removeItemBest(item: Double): Unit = floatList.remove(item)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment