ผลต่างระหว่างรุ่นของ "01204212/codes/zooma"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
แถว 51: แถว 51:
  
 
== Examples of lambda expression ==
 
== Examples of lambda expression ==
 +
 +
Using lambda expression:
 +
 +
<syntaxhighlight lang="java">
 +
pLocation = outComments.findIndex((Comment c) -> (c.getId() == p));
 +
</syntaxhighlight>
 +
 +
Without lambda (anonymous class):
 +
 +
<syntaxhighlight lang="java">
 +
pLocation = outComments.findIndex(new FlexiArray.ItemMatcher<Comment>() {
 +
public boolean isMatch(Comment c) {
 +
return c.getId() == p;
 +
}
 +
});
 +
</syntaxhighlight>

รุ่นแก้ไขเมื่อ 03:34, 25 สิงหาคม 2559

Back to 01204212

FlexiArray.java

public class FlexiArray<T> {

	public interface ItemMatcher<T> {
		boolean isMatch(T item); 
	}
	
	private T[] items;
	private int itemCount;
	private int size;

	@SuppressWarnings("unchecked")
	public FlexiArray(int size) {
		this.items = (T[]) new Object[size];
		this.size = size;
		this.itemCount = 0;
	}
	
	public int findIndex(ItemMatcher<T> matcher) {
		for(int i=0; i<itemCount; i++) {
			if(matcher.isMatch(items[i])) {
				return i;
			}
		}
		return -1;
	}
	
	public void insert(int i, T item) {
		for(int j=itemCount - 1; j >= i; j--) {
			items[j + 1] = items[j];
		}
		items[i] = item;
		itemCount++;
	}

	public void remove(int i) {
		for(int j = i + 1; j < itemCount; j++) {
			items[j - 1] = items[j];
		}
		itemCount--;
	}
	
	public T get(int i) {
		return items[i];
	}
}

Examples of lambda expression

Using lambda expression:

			pLocation = outComments.findIndex((Comment c) -> (c.getId() == p));

Without lambda (anonymous class):

			pLocation = outComments.findIndex(new FlexiArray.ItemMatcher<Comment>() {
				public boolean isMatch(Comment c) {
					return c.getId() == p;
				}
			});