下面列出了java.util.ArrayList#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private DomCard findCardToTrash() {
Collections.sort( owner.getCardsInHand(), SORT_FOR_TRASHING);
DomCard theCardToTrash = owner.getCardsInHand().get( 0 );
if (theCardToTrash==this && owner.getCardsInHand().size()>1)
theCardToTrash = owner.getCardsInHand().get( 1 );
if (owner.countAllCards()<10) {
//this is to enable the 5-card deck of Bishop, 2 Silvers, a Gold and a Province
ArrayList<DomCard> theProvinces = owner.getCardsFromHand(DomCardName.Province);
if (!theProvinces.isEmpty()) {
theCardToTrash=theProvinces.get(0);
}
}
if (!owner.getCardsFromHand(DomCardName.Market_Square).isEmpty() && !owner.getCardsFromHand(DomCardName.Gold).isEmpty())
theCardToTrash=owner.getCardsFromHand(DomCardName.Gold).get(0);
return theCardToTrash;
}
/**
* @param cmmp point to calculate knn distance for
* @param k number of nearest neighbors to look for
* @param pointIDs list of point IDs to check
* @param knnDist sorted list of smallest knn distances (can already be filled to make updates possible)
* @param knnPointIndex list of corresponding knn indices
*/
private void getKnnInCluster(CMMPoint cmmp, int k,
ArrayList<Integer> pointIDs,
AutoExpandVector<Double> knnDist,
AutoExpandVector<Integer> knnPointIndex) {
//iterate over every point in the choosen cluster, cal distance and insert into list
for (int p1 = 0; p1 < pointIDs.size(); p1++) {
int pid = pointIDs.get(p1);
if(cmmp.pID == pid) continue;
double dist = distance(cmmp,cmmpoints.get(pid));
if(knnDist.size() < k || dist < knnDist.get(knnDist.size()-1)){
int index = 0;
while(index < knnDist.size() && dist > knnDist.get(index)) {
index++;
}
knnDist.add(index, dist);
knnPointIndex.add(index,pid);
if(knnDist.size() > k){
knnDist.remove(knnDist.size()-1);
knnPointIndex.remove(knnPointIndex.size()-1);
}
}
}
}
/**
* Inserts Z nodes for every node that needs a new
* successor.
*
* @param result {@code non-null;} method to process
*/
private static void edgeSplitSuccessors(SsaMethod result) {
ArrayList<SsaBasicBlock> blocks = result.getBlocks();
/*
* New blocks are added to the end of the block list during
* this iteration.
*/
for (int i = blocks.size() - 1; i >= 0; i-- ) {
SsaBasicBlock block = blocks.get(i);
// Successors list is modified in loop below.
BitSet successors = (BitSet)block.getSuccessors().clone();
for (int j = successors.nextSetBit(0);
j >= 0; j = successors.nextSetBit(j+1)) {
SsaBasicBlock succ = blocks.get(j);
if (needsNewSuccessor(block, succ)) {
block.insertNewSuccessor(succ);
}
}
}
}
public final int doWork()
{
int workDone = preWork();
final ArrayList<T> sessions = this.sessions;
for (int lastIndex = sessions.size() - 1, i = lastIndex; i >= 0; i--)
{
final T session = sessions.get(i);
try
{
workDone += session.doWork();
}
catch (final Exception ex)
{
errorHandler.onError(ex);
}
if (session.isDone())
{
ArrayListUtil.fastUnorderedRemove(sessions, i, lastIndex--);
closeSession(session);
}
}
return workDone;
}
/**
* Updates the code.
*/
public void update()
{
byte []code = new byte[_code.size()];
System.arraycopy(_code.getBuffer(), 0, code, 0, _code.size());
_codeAttr.setCode(code);
if (_changeLength) {
// XXX: really need more sophisticated solution
ArrayList<Attribute> attrList = getCodeAttribute().getAttributes();
for (int i = attrList.size() - 1; i >= 0; i--) {
Attribute attr = attrList.get(i);
if (attr.getName().equals("LineNumberTable"))
attrList.remove(i);
}
}
}
private static void setupPadding(Bitmap bitmap, NinePatchChunk out) throws WrongPaddingException {
int maxXPixels = bitmap.getWidth() - 2;
int maxYPixels = bitmap.getHeight() - 2;
ArrayList<Div> xPaddings = getXDivs(bitmap, bitmap.getHeight() - 1);
if (xPaddings.size() > 1)
throw new WrongPaddingException("Raw padding is wrong. Should be only one horizontal padding region");
ArrayList<Div> yPaddings = getYDivs(bitmap, bitmap.getWidth() - 1);
if (yPaddings.size() > 1)
throw new WrongPaddingException("Column padding is wrong. Should be only one vertical padding region");
if (xPaddings.size() == 0) xPaddings.add(out.xDivs.get(0));
if (yPaddings.size() == 0) yPaddings.add(out.yDivs.get(0));
out.padding = new Rect();
out.padding.left = xPaddings.get(0).start;
out.padding.right = maxXPixels - xPaddings.get(0).stop;
out.padding.top = yPaddings.get(0).start;
out.padding.bottom = maxYPixels - yPaddings.get(0).stop;
}
public List<WatchableObject> c() {
ArrayList<WatchableObject> arraylist = new ArrayList<WatchableObject>();
this.f.readLock().lock();
arraylist.addAll(this.dataValues.valueCollection());
for (int i = 0; i < arraylist.size(); i++) {
WatchableObject watchableobject = (WatchableObject) arraylist.get(i);
if ((watchableobject.b() instanceof ItemStack)) {
watchableobject = new WatchableObject(watchableobject.c(), watchableobject.a(), ((ItemStack) watchableobject.b()).cloneItemStack());
arraylist.set(i, watchableobject);
}
}
this.f.readLock().unlock();
return arraylist;
}
public Area(Shape shape)
{
int j=0;
PathIterator p=shape.getPathIterator(null);
ArrayList<POINT2>pts=p.getPoints();
POINT2 pt=null;
int n=pts.size();
//for(j=0;j<pts.size();j++)
for(j=0;j<n;j++)
{
pt=pts.get(j);
switch(pt.style)
{
case IPathIterator.SEG_MOVETO:
moveTo(pt.x,pt.y);
break;
case IPathIterator.SEG_LINETO:
lineTo(pt.x,pt.y);
break;
default:
break;
}
}
}
/**
* Remove the mapping from the name of the specified
* {@link LocalVariableGen} to itself.
* See also {@link #registerByName(LocalVariableGen)} and
* {@link #lookUpByName(String)}
* @param lvg a <code>LocalVariableGen</code>
*/
protected void removeByNameTracking(LocalVariableGen lvg) {
Object duplicateNameEntry = _nameToLVGMap.get(lvg.getName());
if (duplicateNameEntry instanceof ArrayList) {
ArrayList sameNameList = (ArrayList) duplicateNameEntry;
for (int i = 0; i < sameNameList.size(); i++) {
if (sameNameList.get(i) == lvg) {
sameNameList.remove(i);
break;
}
}
} else {
_nameToLVGMap.remove(lvg);
}
}
@Test
public void testBlocksScheduledCounter() throws IOException {
cluster = new MiniDFSCluster.Builder(new HdfsConfiguration()).build();
cluster.waitActive();
fs = cluster.getFileSystem();
//open a file an write a few bytes:
FSDataOutputStream out = fs.create(new Path("/testBlockScheduledCounter"));
for (int i=0; i<1024; i++) {
out.write(i);
}
// flush to make sure a block is allocated.
out.hflush();
ArrayList<DatanodeDescriptor> dnList = new ArrayList<DatanodeDescriptor>();
final DatanodeManager dm = cluster.getNamesystem().getBlockManager(
).getDatanodeManager();
dm.fetchDatanodes(dnList, dnList, false);
DatanodeDescriptor dn = dnList.get(0);
assertEquals(1, dn.getBlocksScheduled());
// close the file and the counter should go to zero.
out.close();
assertEquals(0, dn.getBlocksScheduled());
}
@Override
public synchronized DisplayMode[] getDisplayModes() {
ArrayList modes = new ArrayList();
enumDisplayModes(screen, modes);
int listSize = modes.size();
DisplayMode[] retArray = new DisplayMode[listSize];
for (int i = 0; i < listSize; i++) {
retArray[i] = (DisplayMode)modes.get(i);
}
return retArray;
}
/**
* @deprecated May implement this function if METOCs get post clipped
* @param pts2
* @return
*/
private static Shape BuildShapeFromPoints2(ArrayList<POINT2> pts2) {
GeneralPath shape = new GeneralPath();
try {
shape.moveTo(pts2.get(0).x, pts2.get(0).y);
for (int j = 0; j < pts2.size(); j++) {
switch (pts2.get(j).style) {
case 1:
shape.lineTo(pts2.get(j).x, pts2.get(j).y);
break;
case 2:
shape.quadTo(pts2.get(j).x, pts2.get(j).y, pts2.get(j + 1).x, pts2.get(j + 1).y);
j++;
break;
case 3:
shape.curveTo(pts2.get(j).x, pts2.get(j).y, pts2.get(j + 1).x, pts2.get(j + 1).y, pts2.get(j + 2).x, pts2.get(j + 2).y);
j += 2;
break;
case 4:
shape.lineTo(pts2.get(0).x, pts2.get(0).y);
break;
default:
shape.lineTo(pts2.get(0).x, pts2.get(0).y);
break;
}//end switch
}//end for
}//end try
catch (Exception exc) {
ErrorLogger.LogException(_className, "BuildShapeFromPoints2",
new RendererException("Failed inside BuildShapeFromPoints2", exc));
}
return shape;
}
private void signCertificateChain() {
ArrayList cc = new ArrayList();
cc.add(signCert);
ArrayList oc = new ArrayList(certs);
for (int k = 0; k < oc.size(); ++k) {
if (signCert.getSerialNumber().equals(((X509Certificate)oc.get(k)).getSerialNumber())) {
oc.remove(k);
--k;
continue;
}
}
boolean found = true;
while (found) {
X509Certificate v = (X509Certificate)cc.get(cc.size() - 1);
found = false;
for (int k = 0; k < oc.size(); ++k) {
try {
if (provider == null)
v.verify(((X509Certificate)oc.get(k)).getPublicKey());
else
v.verify(((X509Certificate)oc.get(k)).getPublicKey(), provider);
found = true;
cc.add(oc.get(k));
oc.remove(k);
break;
}
catch (Exception e) {
}
}
}
signCerts = cc;
}
@SuppressWarnings("unchecked")
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
boolean found = false;
ArrayList<AbstractInsnNode>[] allNodes = (ArrayList<AbstractInsnNode>[]) Array.newInstance(ArrayList.class, this.components.length);
for (int i = 0; i < this.components.length; i++) {
allNodes[i] = new ArrayList<AbstractInsnNode>();
this.components[i].find(desc, insns, allNodes[i]);
}
ArrayList<AbstractInsnNode> alpha = allNodes[0];
for (int nodeIndex = 0; nodeIndex < alpha.size(); nodeIndex++) {
AbstractInsnNode node = alpha.get(nodeIndex);
boolean in = true;
for (int b = 1; b < allNodes.length; b++) {
if (!allNodes[b].contains(node)) {
break;
}
}
if (!in) {
continue;
}
nodes.add(node);
found = true;
}
return found;
}
/**
* Applies the optimization.
*/
private void run() {
int regSz = ssaMeth.getRegCount();
ArrayList<TypedConstant> constantList
= getConstsSortedByCountUse();
int toCollect = Math.min(constantList.size(), MAX_COLLECTED_CONSTANTS);
SsaBasicBlock start = ssaMeth.getEntryBlock();
// Constant to new register containing the constant
HashMap<TypedConstant, RegisterSpec> newRegs
= new HashMap<TypedConstant, RegisterSpec> (toCollect);
for (int i = 0; i < toCollect; i++) {
TypedConstant cst = constantList.get(i);
RegisterSpec result
= RegisterSpec.make(ssaMeth.makeNewSsaReg(), cst);
Rop constRop = Rops.opConst(cst);
if (constRop.getBranchingness() == Rop.BRANCH_NONE) {
start.addInsnToHead(
new PlainCstInsn(Rops.opConst(cst),
SourcePosition.NO_INFO, result,
RegisterSpecList.EMPTY, cst));
} else {
// We need two new basic blocks along with the new insn
SsaBasicBlock entryBlock = ssaMeth.getEntryBlock();
SsaBasicBlock successorBlock
= entryBlock.getPrimarySuccessor();
// Insert a block containing the const insn.
SsaBasicBlock constBlock
= entryBlock.insertNewSuccessor(successorBlock);
constBlock.replaceLastInsn(
new ThrowingCstInsn(constRop, SourcePosition.NO_INFO,
RegisterSpecList.EMPTY,
StdTypeList.EMPTY, cst));
// Insert a block containing the move-result-pseudo insn.
SsaBasicBlock resultBlock
= constBlock.insertNewSuccessor(successorBlock);
PlainInsn insn
= new PlainInsn(
Rops.opMoveResultPseudo(result.getTypeBearer()),
SourcePosition.NO_INFO,
result, RegisterSpecList.EMPTY);
resultBlock.addInsnToHead(insn);
}
newRegs.put(cst, result);
}
updateConstUses(newRegs, regSz);
}
/**
* Streamlined bulk insertion to initialize from elements of
* given sorted map. Call only from constructor or clone
* method.
*/
private void buildFromSorted(SortedMap<K, ? extends V> map) {
if (map == null)
throw new NullPointerException();
HeadIndex<K,V> h = head;
Node<K,V> basepred = h.node;
// Track the current rightmost node at each level. Uses an
// ArrayList to avoid committing to initial or maximum level.
ArrayList<Index<K,V>> preds = new ArrayList<Index<K,V>>();
// initialize
for (int i = 0; i <= h.level; ++i)
preds.add(null);
Index<K,V> q = h;
for (int i = h.level; i > 0; --i) {
preds.set(i, q);
q = q.down;
}
Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<? extends K, ? extends V> e = it.next();
int rnd = ThreadLocalRandom.current().nextInt();
int j = 0;
if ((rnd & 0x80000001) == 0) {
do {
++j;
} while (((rnd >>>= 1) & 1) != 0);
if (j > h.level) j = h.level + 1;
}
K k = e.getKey();
V v = e.getValue();
if (k == null || v == null)
throw new NullPointerException();
Node<K,V> z = new Node<K,V>(k, v, null);
basepred.next = z;
basepred = z;
if (j > 0) {
Index<K,V> idx = null;
for (int i = 1; i <= j; ++i) {
idx = new Index<K,V>(z, idx, null);
if (i > h.level)
h = new HeadIndex<K,V>(h.node, h, idx, i);
if (i < preds.size()) {
preds.get(i).right = idx;
preds.set(i, idx);
} else
preds.add(idx);
}
}
}
head = h;
}
private final boolean findMimeType(String type) {
final ArrayList<String> t = mDataTypes;
if (type == null) {
return false;
}
if (t.contains(type)) {
return true;
}
// Deal with an Intent wanting to match every type in the IntentFilter.
final int typeLength = type.length();
if (typeLength == 3 && type.equals("*/*")) {
return !t.isEmpty();
}
// Deal with this IntentFilter wanting to match every Intent type.
if (mHasPartialTypes && t.contains("*")) {
return true;
}
final int slashpos = type.indexOf('/');
if (slashpos > 0) {
if (mHasPartialTypes && t.contains(type.substring(0, slashpos))) {
return true;
}
if (typeLength == slashpos+2 && type.charAt(slashpos+1) == '*') {
// Need to look through all types for one that matches
// our base...
final int numTypes = t.size();
for (int i = 0; i < numTypes; i++) {
final String v = t.get(i);
if (type.regionMatches(0, v, 0, slashpos+1)) {
return true;
}
}
}
}
return false;
}
/**
* Processes all the rules and builds a DateTimeZone.
*
* @param id time zone id to assign
* @param outputID true if the zone id should be output
*/
public DateTimeZone toDateTimeZone(String id, boolean outputID) {
if (id == null) {
throw new IllegalArgumentException();
}
// Discover where all the transitions occur and store the results in
// these lists.
ArrayList<Transition> transitions = new ArrayList<Transition>();
// Tail zone picks up remaining transitions in the form of an endless
// DST cycle.
DSTZone tailZone = null;
long millis = Long.MIN_VALUE;
int saveMillis = 0;
int ruleSetCount = iRuleSets.size();
for (int i=0; i<ruleSetCount; i++) {
RuleSet rs = iRuleSets.get(i);
Transition next = rs.firstTransition(millis);
if (next == null) {
continue;
}
addTransition(transitions, next);
millis = next.getMillis();
saveMillis = next.getSaveMillis();
// Copy it since we're going to destroy it.
rs = new RuleSet(rs);
while ((next = rs.nextTransition(millis, saveMillis)) != null) {
if (addTransition(transitions, next)) {
if (tailZone != null) {
// Got the extra transition before DSTZone.
break;
}
}
millis = next.getMillis();
saveMillis = next.getSaveMillis();
if (tailZone == null && i == ruleSetCount - 1) {
tailZone = rs.buildTailZone(id);
// If tailZone is not null, don't break out of main loop until
// at least one more transition is calculated. This ensures a
// correct 'seam' to the DSTZone.
}
}
millis = rs.getUpperLimit(saveMillis);
}
// Check if a simpler zone implementation can be returned.
if (transitions.size() == 0) {
if (tailZone != null) {
// This shouldn't happen, but handle just in case.
return tailZone;
}
return buildFixedZone(id, "UTC", 0, 0);
}
if (transitions.size() == 1 && tailZone == null) {
Transition tr = transitions.get(0);
return buildFixedZone(id, tr.getNameKey(),
tr.getWallOffset(), tr.getStandardOffset());
}
PrecalculatedZone zone = PrecalculatedZone.create(id, outputID, transitions, tailZone);
if (zone.isCachable()) {
return CachedDateTimeZone.forZone(zone);
}
return zone;
}
public Object[] delete(Service S) {
ArrayList dellist = new ArrayList(), newlist = new ArrayList();
if (S.level == null) {
Object[] result = get("None");
reinit();
return result;
}
makeConsistent(S);
// Get the actual vector index
int mylevel = S.actualLevel;
if (stack.get(mylevel) == null)
return dellist.toArray();
ArrayList srv = (ArrayList) stack.get(mylevel);
Service temp;
pr("Deleting : " + S);
for (int i = 0; i < srv.size(); i++) {
temp = (Service) srv.get(i);
pr("Checking : " + temp);
if (!(temp.toString().equals(S.toString()))) {
newlist.add(temp);
} else {
pr("Delete match : " + temp.toString());
dellist.add(temp);
}
}
if (newlist.size() == 0) {
stack.set(mylevel, null);
// Decrease the stack size
while (toplevel > 0 && stack.get(toplevel) == null)
toplevel--;
} else {
stack.setElementAt(newlist, mylevel);
}
return dellist.toArray();
}
/**
* Used eg. if the player gets stuck and can't move any further: Mix all cards randomly by
* exchanging them with other cards. The games can exclude cards to mix, like all cards on the
* foundation, or complete sequences.
*/
public void mixCards() {
Random random = getPrng();
ArrayList<Card> cardsToMix = new ArrayList<>();
int counter;
Card cardToChange;
//getHighScore the cards to mix
for (Card card : cards) {
if (!excludeCardFromMixing(card)) {
cardsToMix.add(card);
}
}
//exchange cards. A bit like Fisher-Yate Shuffle, but the iterating array doesn't change.
for (int i = cardsToMix.size() - 1; i >= 0; i--) {
if (prefs.getSavedUseTrueRandomisation()) {
cardToChange = cardsToMix.get(random.nextInt(i + 1));
} else {
//choose a new card as long the chosen card is too similar to the previous and following card in the array
//(same value or color) also limit the loop to max 10 iterations to avoid infinite loops
counter = 0;
do {
cardToChange = cardsToMix.get(random.nextInt(i + 1));
counter++;
}
while ( //the card below cardToChange shouldn't be too similar (but only if there is a card below)
(!cardToChange.isFirstCard() && (cardToChange.getCardBelow().getValue() == cardsToMix.get(i).getValue() || cardToChange.getCardBelow().getColor() == cardsToMix.get(i).getColor())
//the card on top cardToChange shouldn't be too similar (but only if there is a card on top)
|| !cardToChange.isTopCard() && (cardToChange.getCardOnTop().getValue() == cardsToMix.get(i).getValue() || cardToChange.getCardOnTop().getColor() == cardsToMix.get(i).getColor()))
//and the loop shouldn't take too long
&& counter < 10);
}
cardToChange.getStack().exchangeCard(cardToChange, cardsToMix.get(i));
}
sounds.playSound(Sounds.names.DEAL_CARDS);
//After every card got a new place, update the card image views
for (Stack stack : stacks) {
stack.updateSpacing();
}
//delete the record list, otherwise undoing movements would result in strange behavior
recordList.reset();
handlerTestAfterMove.sendDelayed();
}