Created
November 27, 2013 15:46
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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