Groovy getAt()vs get()

时间:2014-03-25 07:15:03

标签: groovy

考虑清单:
def list = [1, 2, 3]
如果我使用
list.getAt(0)

list.get(0)
两者都会给出相同的输出 但getAt()和get()之间是否存在差异?

2 个答案:

答案 0 :(得分:14)

The documentation解释道:

  

支持列表的下标运算符。

def list = [2, "a", 5.3]
assert list[1] == "a"

所以没有区别,但getAt()是允许Groovy代码使用list[1]代替list.get(1)的方法

有关运算符重载的工作原理,请参阅http://groovy.codehaus.org/Operator+Overloading

答案 1 :(得分:7)

文档没有很好地解释这一点,但实际上我的测试中的差异似乎是getAt(i)在引用列表中实际不存在的索引时将返回null,而get(i)将返回class BookView: UIScrollView { var bookMarkup: NSAttributedString! private let layoutManager = NSLayoutManager() override func layoutSubviews() { super.layoutSubviews() if layoutManager.textContainers.count == 0 { buildFrames() } } func buildFrames() { let textStorage = NSTextStorage(attributedString: bookMarkup) textStorage.addLayoutManager(layoutManager) var range = NSMakeRange(0, 0) var containerIndex = 0 while NSMaxRange(range) < layoutManager.numberOfGlyphs { let textViewRect = frameForViewAtIndex(containerIndex) let containerSize = CGSizeMake(CGRectGetWidth(textViewRect), CGRectGetHeight(textViewRect) - 16) //UITextView adds an 8 margin above and below the container so we take that into consideration here with the 16. heightTracksTextView causes a performance hit when adding multiple containers... so we don't do that instead let textContainer = NSTextContainer(size: containerSize) layoutManager.addTextContainer(textContainer) let textView = UITextView(frame: textViewRect, textContainer: textContainer) addSubview(textView) containerIndex++ range = layoutManager.glyphRangeForTextContainer(textContainer) } contentSize = CGSize(width: CGRectGetWidth(bounds) / 2 * CGFloat(containerIndex), height: CGRectGetHeight(bounds)) pagingEnabled = true } private func frameForViewAtIndex(index: Int) -> CGRect { var textViewRect = CGRect(origin: CGPointZero, size: CGSize(width: CGRectGetWidth(bounds)/2, height: CGRectGetHeight(bounds))) textViewRect = CGRectInset(textViewRect, 10, 20) textViewRect = CGRectOffset(textViewRect, CGRectGetWidth(bounds) / 2 * CGFloat(index), 0) return textViewRect } } 当传入不在列表中的索引时,方法将抛出 IndexOutOfBoundsException ,就像普通的旧Java一样。