/** @tests java.util.ArrayList#ensureCapacity(int) */ public void test_ensureCapacityI() { // Test for method void java.util.ArrayList.ensureCapacity(int) // TODO : There is no good way to test this as it only really impacts on // the private implementation. Object testObject = new Object(); int capacity = 20; ArrayList al = new ArrayList(capacity); int i; for (i = 0; i < capacity / 2; i++) { al.add(i, new Object()); } al.add(i, testObject); int location = al.indexOf(testObject); al.ensureCapacity(capacity); assertTrue( "EnsureCapacity moved objects around in array1.", location == al.indexOf(testObject)); al.remove(0); al.ensureCapacity(capacity); assertTrue( "EnsureCapacity moved objects around in array2.", --location == al.indexOf(testObject)); al.ensureCapacity(capacity + 2); assertTrue("EnsureCapacity did not change location.", location == al.indexOf(testObject)); ArrayList<String> list = new ArrayList<String>(1); list.add("hello"); list.ensureCapacity(Integer.MIN_VALUE); }
// find commits that are (only?) in each remote private void getCommitsInR(RevWalk walk, boolean only) throws MissingObjectException, IncorrectObjectTypeException, IOException { Iterator<BranchRef> brIt; LinkedHashMap<String, ArrayList<Commit>> commits; ArrayList<RevCommit> comm; ArrayList<RevCommit> included = new ArrayList<RevCommit>(); ArrayList<RevCommit> excluded = new ArrayList<RevCommit>(); Entry<String, ArrayList<BranchRef>> er; String r; Commit c; ArrayList<Commit> newcos; Iterator<Entry<String, ArrayList<BranchRef>>> erit; Iterator<String> sit = branches.keySet().iterator(); commits = new LinkedHashMap<String, ArrayList<Commit>>(branches.size() / 2, 1); if (only) excluded.ensureCapacity(allBranches.size() - 1); // int j = 0; while (sit.hasNext()) { /**/ // System.err.println("###### Iteration " + (++j)); r = sit.next(); erit = branches.entrySet().iterator(); while (erit.hasNext()) { er = erit.next(); brIt = er.getValue().iterator(); if (er.getKey().equals(r)) { while (brIt.hasNext()) { GitWorks.addUnique(included, walk.parseCommit(brIt.next().id)); } } else if (only) { while (brIt.hasNext()) { GitWorks.addUnique(excluded, walk.parseCommit(brIt.next().id)); } } } comm = findCommits(walk, included, excluded, false, 0); if (comm != null) { newcos = new ArrayList<Commit>(comm.size()); for (int i = 0; i < comm.size(); i++) { c = GitWorks.getElement(allCommits, comm.get(i)); newcos.add(c); } commits.put(r, newcos); } included.clear(); excluded.clear(); walk.reset(); } included.trimToSize(); included.ensureCapacity(50); excluded.trimToSize(); excluded.ensureCapacity(50); if (only) comOnlyInF = commits.isEmpty() ? null : commits; else comInF = commits.isEmpty() ? null : commits; }
/** Creates a MergedDeck from the given Decks. */ public MergedDeck(Deck... decks) { this.decks = decks; ArrayList<Card> cards = new ArrayList<Card>(); cards.ensureCapacity(decks.length * 52); for (Deck d : decks) cards.addAll(Arrays.asList(d.getCards())); this.cards = cards.toArray(new Card[0]); ArrayList<Card> jokers = new ArrayList<Card>(); jokers.ensureCapacity(decks.length * 2); for (Deck d : decks) jokers.addAll(Arrays.asList(d.getJokers())); this.jokers = jokers.toArray(new Card[0]); }
private static void addNewInfo( Map<Class, DomainClassInfo> map, ArrayList<DomainClassInfo> array, DomainClassInfo info) { if (logger.isDebugEnabled()) { logger.debug( "Registering new domain class '" + info.domainClass.getName() + "' with id " + info.classId); } if (info.domainClass != null) { map.put(info.domainClass, info); } int index = info.classId; int size = array.size(); if (size <= index) { array.ensureCapacity(index + 1); while (size < index) { array.add(null); size++; } array.add(info); } else { array.set(info.classId, info); } }
public String decodeContextualValue(DataInputStream in) throws IOException { String res; int id = in.readInt(); if (id == 0) { res = null; } else if (id > 0) { // "(+)id" : existing value res = idToValue.get(id); } else { // id < 0 // "-id,value" id = -id; res = in.readUTF(); // register newly id (not needed when re-reading from context) if (id > idGenerator) { idGenerator = id + 1; // ?? if (idToValue.size() < id) { idToValue.ensureCapacity(id); for (int i = idToValue.size(); i < id; i++) { idToValue.add(null); } } idToValue.set(id, res); valueToId.put(res, Integer.valueOf(id)); } // else re-read value.. } return res; }
// Constructors // ---------------------------------------------------------- public IndividualRecord(String tmpid) { id = tmpid; fams = new ArrayList<String>(); birth = null; death = null; marriage = null; middleName = ""; mother = null; father = null; fontsize = 12; // printf(tmpid.c_str()); photoxoffset = 25; // this is how far from the far left corner of the bounding box the name will start. // This is how much space the photo gets fontsize = 16; linesofinfo = 0; xsepvalue = 0; x = 0; y = 0; intree = false; drawn = false; c = 0; c2 = 0; c3 = 0; center = 0; gender = 0; fams.clear(); fams.ensureCapacity(0); }
// the RevWalk must be reset by the caller upon return! private ArrayList<RevCommit> findCommits( RevWalk walk, ArrayList<RevCommit> included, ArrayList<RevCommit> excluded, boolean getBody, long after) throws MissingObjectException, IncorrectObjectTypeException, IOException { ArrayList<RevCommit> commits = new ArrayList<RevCommit>(); commits.ensureCapacity(allBranches.size()); // heuristic workaround walk.sort(RevSort.COMMIT_TIME_DESC, true); walk.sort(RevSort.TOPO, true); walk.setRetainBody(getBody); if (after > 0) walk.setRevFilter(CommitTimeRevFilter.after(after)); else walk.setRevFilter(null); walk.markStart(included); RevCommit c; Iterator<RevCommit> it = excluded.iterator(); while (it.hasNext()) { walk.markUninteresting(it.next()); } it = walk.iterator(); while (it.hasNext()) { c = it.next(); if (getBody) walk.parseBody(c); // addUnique(commits, c); // commits are naturally ordered by SHA-1 commits.add(c); } return commits.size() > 0 ? commits : null; }
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.list___imul___doc) final synchronized PyObject list___imul__(PyObject o) { if (!o.isIndex()) { return null; } int count = o.asIndex(Py.OverflowError); int size = size(); if (size == 0 || count == 1) { return this; } if (count < 1) { clear(); return this; } if (size > Integer.MAX_VALUE / count) { throw Py.MemoryError(""); } int newSize = size * count; if (list instanceof ArrayList) { ((ArrayList) list).ensureCapacity(newSize); } List<PyObject> oldList = new ArrayList<PyObject>(list); for (int i = 1; i < count; i++) { list.addAll(oldList); } gListAllocatedStatus = __len__(); // now omit? return this; }
/** Creates a new instance of VariationsTableModel */ public VariationsTableModel() { _rows = VariationsFactory.getVariationQuantity(); int maxAdditionalParams = 0; _parameters.ensureCapacity(_rows); _coefficients.ensureCapacity(_rows); for (int i = 0; i < _rows; i++) { _coefficients.add(Double.valueOf(0)); IVariation tmp = VariationsFactory.getVariation(i, Double.valueOf(0)); int parametersQuantity = tmp.getParametersQuantity(); ArrayList<Double> parameters = new ArrayList<>(parametersQuantity); for (int j = 0; j < parametersQuantity; j++) { parameters.add(Double.valueOf(0)); } _parameters.add(parameters); if (maxAdditionalParams < parametersQuantity) { maxAdditionalParams = parametersQuantity; } } _columns = 2 + maxAdditionalParams; }
private synchronized void sort(PyObject cmp, PyObject key, boolean reverse) { gListAllocatedStatus = -1; int size = list.size(); final ArrayList<KV> decorated = new ArrayList<KV>(size); for (PyObject value : list) { decorated.add(new KV(key.__call__(value), value)); } list.clear(); KVComparator c = new KVComparator(this, cmp); if (reverse) { Collections.reverse(decorated); // maintain stability of sort by reversing first } Collections.sort(decorated, c); if (reverse) { Collections.reverse(decorated); } if (list instanceof ArrayList) { ((ArrayList) list).ensureCapacity(size); } for (KV kv : decorated) { list.add(kv.value); } gListAllocatedStatus = __len__(); }
/** * Sets a property based on the index. According to C.6.13.1 if the index is greater than the * current number of nodes, expand the size by one and add the new value to the end. * * @param index The index of the property to set * @param start The object who's property is being set * @param value The value being requested */ public void put(int index, Scriptable start, Object value) { if (readOnly && !scriptField) { Context.reportError(READONLY_MSG); return; } if (!(value instanceof SFVec2d)) { Context.reportError(OBJECT_NOT_VEC_MSG); return; } Scriptable node = (SFVec2d) value; if (node.getParentScope() == null) node.setParentScope(this); if (index >= valueList.size()) { int toAdd = index - valueList.size(); valueList.ensureCapacity(index + 1); // Add default values for (int i = 0; i < toAdd; i++) { valueList.add(new SFVec2d()); } valueList.add(value); sizeInt.setValue(valueList.size()); } else if (index >= 0) { valueList.set(index, value); } dataChanged = true; }
@Override public void load(Menu menu, BinaryFile bin, short version) { switch (version) { case 0: { name = bin.getString(); anchor.load(bin); break; } case 1: { name = bin.getString(); anchor.load(bin); if (bin.getBoolean()) { int layoutId = bin.getInt(); layout = MenuComponentFactory.newLayoutInstance(layoutId, version, menu, bin); } int scriptCount = bin.getInt(); scripts.ensureCapacity(scriptCount); for (int i = 0; i < scriptCount; i++) { scripts.add(bin.getString()); } break; } default: throw new RuntimeException(); } }
/** * Utility method to perform all processing on a new ItemizedOverlay. Subclasses provide Items * through the createItem(int) method. The subclass should call this as soon as it has data, * before anything else gets called. */ protected final void populate() { final int size = size(); mInternalItemList.clear(); mInternalItemList.ensureCapacity(size); for (int a = 0; a < size; a++) { mInternalItemList.add(createItem(a)); } }
/** Adds point to point list and keeps track of largest coordinate. */ public final void addPoint(int pos, double x, double y) { PathPoint p = new PathPoint(x, y, true); updateBounds(p); pathPoints.ensureCapacity(pos + 1); while (pathPoints.size() <= pos) { pathPoints.add(null); } pathPoints.set(pos, p); }
public List<Integer> doStuff() { testArrayList.add(1); testLinkedList.add(1); int j = 2; String testNull = ""; /** @JDSA:j:small */ while (j < 3) { testArrayList.add(j); testLinkedList.add(j); j++; } while (testNull != null) { if (j > 6) { testNull = null; } j++; } System.out.println("Past while"); for (int i = 3; i < 101; i++) { testArrayList.add(i); testLinkedList.add(i); } System.out.println("Past 101 loop"); for (Integer k : testArrayList) { testLinkedList.add(k + 1000); } System.out.println("Past arraylist foreach"); // Testing nested loop. Should get O(n^2) for (Integer b : testArrayList) { for (Integer l : testLinkedList) { testArrayList.add(l + b + 1000); } } System.out.println("Past linked list foreach"); // Shouldn't get O(n) for the size call here. Need to fix that part. for (int i = 1; i < testArrayList.size(); i++) { testLinkedList.add(i ^ 2 + 2000); } int tempVar = 0; for (int i = 0; i < testLinkedList.size(); i++) { tempVar = testLinkedList.get(i); if (testArrayList.size() < tempVar) { testArrayList.remove(tempVar); } } // Add a method that isn't available for LinkedLists // (It just adds an O() method and doesn't error - Expected behaviour) testArrayList.ensureCapacity(testArrayList.size()); // Testing chained methods (Should just be get - it is :) ) testArrayList.get(0).intValue(); System.out.println("Past Array list size loop"); System.out.println(testVar); System.out.println((testArrayList.get(testArrayList.size() - 1) - testArrayList.get(0))); System.out.println(testLinkedList.get(testLinkedList.size() - 1)); return testArrayList; }
/** PRAGMA: All Edge in list have p as predicate Use case: Rule Engine */ public void add(Node p, List<Entity> list) { ArrayList<Entity> l = define(p); if (index == 0 || l.size() > 0) { l.ensureCapacity(l.size() + list.size()); l.addAll(list); } if (index == 0) { isUpdate = true; } }
private final void setsliceList(int start, int stop, int step, List value) { int n = sliceLength(start, stop, step); if (list instanceof ArrayList) { ((ArrayList) list).ensureCapacity(start + n); } ListIterator src = value.listIterator(); for (int j = start; src.hasNext(); j += step) { set(j, src.next()); } }
public void addList(ArrayList<LimitBuyGoods> list) { if (list == null) { return; } limitbuyList.ensureCapacity(limitbuyList.size() + list.size()); for (LimitBuyGoods limitbuy : list) { limitbuyList.add(limitbuy); } notifyDataSetChanged(); }
public void appendEntries(ENTRY[] entries) { if (entries != null && entries.length > 0) { fItems.ensureCapacity(fItems.size() + entries.length); for (int i = 0; i < entries.length; i++) { fItems.add(entries[i]); } onAppendDone(entries); } notifyOnChanged(); }
public void updateList(List<LimitBuyGoods> list) { limitbuyList.clear(); if (limitbuyList != null) { limitbuyList.ensureCapacity(list.size()); for (LimitBuyGoods limitbuy : list) { limitbuyList.add(limitbuy); } } this.notifyDataSetChanged(); }
/** * Adds each element of {@code elements} to the {@code ImmutableList}. * * @param elements the {@code Iterable} to add to the {@code ImmutableList} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is or contains null */ public Builder<E> addAll(Iterable<? extends E> elements) { if (elements instanceof Collection) { @SuppressWarnings("unchecked") Collection<? extends E> collection = (Collection<? extends E>) elements; contents.ensureCapacity(contents.size() + collection.size()); } for (E elem : elements) { Preconditions.checkNotNull(elem, "elements contains a null"); contents.add(elem); } return this; }
public void initialize() { int lineCount = snapshot.getLineCount(); if (lineStates.size() != lineCount) { lineStates.ensureCapacity(lineCount); TState dirtyState = getStartState().createDirtyState(); for (int i = lineStates.size(); i < lineCount; i++) { lineStates.add(dirtyState); } forceRehighlightLines(0, lineCount - 1); } }
/** * This method initialises the sentry points. The following steps are followed: * * <ol> * <li>Randomly selects an {@link Entity} from the given {@link Topology} * <li>Clones the selected entity a {@link #numberOfSentries specified} number of times * <li>Reinitialises each cloned entity * <li>Evaluates each cloned entity (fitness value is calculated) * <li>Adds each cloned entity to the list of sentry points * </ol> * * @param topology the topology holding all the entities in the population * @throws an {@link IllegalStateException} when this method is called and {@link #sentries} is * NOT <code>null</code>. */ private void initialiseSentryPoints(Topology<? extends Entity> topology) { int size = Double.valueOf(numberOfSentries.getParameter()).intValue(); Entity prototype = (Entity) new RandomSelector().on(topology).select(); sentries.ensureCapacity(size); for (int i = 0; i < size; ++i) { Entity sentry = prototype.getClone(); sentry.reinitialise(); sentry.calculateFitness(); sentries.add(sentry); } }
// build both the allBranches sorted arrayList and the branches map private void buildBranchesMap(int size) throws GitAPIException { if (branches != null) { System.err.println( "GitMIner ( " + name + " -- " + id + " ) ERROR : the map of the branches has already been built!"); return; } branches = new LinkedHashMap<String, ArrayList<BranchRef>>(size, 1); allBranches = new ArrayList<BranchRef>(); ArrayList<BranchRef> temp = null; BranchRef br; Ref r; ArrayList<Ref> all = (ArrayList<Ref>) git.branchList().setListMode(ListMode.REMOTE).call(); Iterator<Ref> allBs = all.iterator(); String bName = ""; allBranches.ensureCapacity(all.size()); // int j = 0; while (allBs.hasNext()) { /**/ // System.err.println("###### Iteration " + (++j)); r = allBs.next(); if (!(r.getName().split("/")[2]).equals(bName)) { bName = r.getName().split("/")[2]; // getName() format: // refs/remotes/<remote-name>/<branch-name> if (temp != null) temp.trimToSize(); temp = new ArrayList<BranchRef>(); branches.put(bName, temp); } br = new BranchRef(r); temp.add(br); allBranches.add(br); } allBranches.trimToSize(); Collections.sort(allBranches); for (int i = 0; i < allBranches.size(); i++) { allBranches.get(i).index = i; } // Entry<String, ArrayList<BranchRef>> e; // Iterator<Entry<String, ArrayList<BranchRef>>> eit = branches.entrySet().iterator(); // while (eit.hasNext()) { // e = eit.next(); // System.out.println("\t" + e.getKey() + ":\n"); // printAny(e.getValue(), System.out); // } // printArray(allBranches, System.out); }
/** * Fill the client Data table from an Android Cursor Database * * @param pCursor */ public void fillFromCursor(Cursor pCursor) { _mCursor = pCursor; _mCursorSize = pCursor.getCount(); _mListOfRows.clear(); _mListOfRows.ensureCapacity(_mCursorSize); String[] lCursorColumnsNames = pCursor.getColumnNames(); int lNbrColumnsCDT = getColumnsCount(); int lNbrColumnsCursor = lCursorColumnsNames.length; if (lNbrColumnsCDT == 0) { for (int i = 0; i < lNbrColumnsCursor; i++) { _mListOfColumns.add(new TColumn(lCursorColumnsNames[i], ValueType.TEXT)); } } if (_mCursorSize > 0) { pCursor.moveToFirst(); _mPosition = 0; while (!pCursor.isAfterLast()) { TRow lRow = new TRow(); if (lNbrColumnsCDT > 0) { for (int i = 0; i < lNbrColumnsCDT; i++) { boolean lIsColumnFound = false; TColumn lColumn = _mListOfColumns.get(i); for (int j = 0; j < lNbrColumnsCursor; j++) { if (lColumn != null && lColumn.getName().equals(lCursorColumnsNames[j])) { lRow.addCell(_mContext, pCursor.getString(j), lColumn.getValueType(), _mCDTStatus); lIsColumnFound = true; break; } } if (!lIsColumnFound) lRow.addCell(_mContext, "", lColumn.getValueType(), _mCDTStatus); } } else { for (int i = 0; i < lNbrColumnsCursor; i++) { String lColumnName = lCursorColumnsNames[i]; if (lColumnName != null && !lColumnName.equals("")) lRow.addCell(_mContext, pCursor.getString(i), ValueType.TEXT, _mCDTStatus); } } _mListOfRows.add(lRow); pCursor.moveToNext(); } } Log.i("fillFromCursor", " Count :" + _mCursorSize); }
@Override public List<Track> getAllTracks() { Cursor cursor = getTrackCursor(null, null, null, TracksColumns._ID); ArrayList<Track> tracks = new ArrayList<Track>(); if (cursor != null) { tracks.ensureCapacity(cursor.getCount()); if (cursor.moveToFirst()) { do { tracks.add(createTrack(cursor)); } while (cursor.moveToNext()); } cursor.close(); } return tracks; }
@Deprecated public void addParameterValues(String key, String[] newValues) { if (key == null) { return; } ArrayList<String> values = paramHashValues.get(key); if (values == null) { values = new ArrayList<String>(newValues.length); paramHashValues.put(key, values); } else { values.ensureCapacity(values.size() + newValues.length); } for (String newValue : newValues) { values.add(newValue); } }
/** Construct a field based on a flattened array of data (sourced from a node). */ public MFVec2d(double[] values, int numValid) { this(); int elements = numValid / 2; if (numValid != 0) { doubleData = new double[numValid]; System.arraycopy(values, 0, doubleData, 0, numValid); // back fill the list with empty data. valueList.ensureCapacity(elements); for (int i = 0; i < elements; i++) valueList.add(null); } sizeInt.setValue(elements); }
public void loadConfiguration(Configuration configuration) { imagesList.clear(); String directory = configuration.getDirectory(); int maxSize = ImageHolder.coerceInteger(configuration.getMaxSize()); if (directory != null && !directory.isEmpty()) { File dir = new File(directory); File[] files = dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { String lowerName = name.toLowerCase(); return lowerName.endsWith(".jpg") || lowerName.endsWith(".png") || lowerName.endsWith(".gif"); } }); if (files != null && files.length > 0) { imagesList.ensureCapacity(files.length); for (File file : files) { if (file.isFile()) { imagesList.add(new ImageHolder(file, maxSize)); } } imagesList.trimToSize(); } } boolean useTimer = configuration.isUseTimer(); if (useTimer) { if (timer.isRunning()) { timer.restart(); } else { timer.start(); } } else { if (timer.isRunning()) { timer.stop(); } } for (Editor editor : editorsList) { loadImage(editor); } }
private String[] getAllKeys() { ArrayList<String> list = new ArrayList<String>(); synchronized (context) { for (int scope : context.getScopes()) { Bindings bindings = context.getBindings(scope); if (bindings != null) { list.ensureCapacity(bindings.size()); for (String key : bindings.keySet()) { list.add(key); } } } } String[] res = new String[list.size()]; list.toArray(res); return res; }