Java Code Examples for java.util.ArrayList#ensureCapacity()

The following examples show how to use java.util.ArrayList#ensureCapacity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JournalVoucherAction.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method will clear out the source line values that aren't needed for the "Single Amount" mode.
 * 
 * @param journalVoucherForm
 */
protected void switchFromSingleAmountModeToCreditDebitMode(JournalVoucherForm journalVoucherForm) {
    // going from single amount to credit/debit view so we want to blank out the amount and the extra "reference" fields
    // that the single amount view uses
    JournalVoucherDocument jvDoc = (JournalVoucherDocument) journalVoucherForm.getTransactionalDocument();
    ArrayList sourceLines = (ArrayList) jvDoc.getSourceAccountingLines();
    ArrayList helperLines = (ArrayList) journalVoucherForm.getVoucherLineHelpers();
    helperLines.clear(); // reset so we can add in fresh empty ones

    // make sure that there is enough space in the list
    helperLines.ensureCapacity(sourceLines.size());

    for (int i = 0; i < sourceLines.size(); i++) {
        VoucherSourceAccountingLine sourceLine = (VoucherSourceAccountingLine) sourceLines.get(i);
        sourceLine.setAmount(KualiDecimal.ZERO);
        sourceLine.setDebitCreditCode(KFSConstants.GL_DEBIT_CODE); // default to debit

        helperLines.add(new VoucherAccountingLineHelperBase()); // populate with a fresh new empty object
    }
}
 
Example 2
Source File: SessionReportingCoordinator.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@NonNull
private static List<CustomAttribute> getSortedCustomAttributes(
    @NonNull Map<String, String> attributes) {
  ArrayList<CustomAttribute> attributesList = new ArrayList<>();
  attributesList.ensureCapacity(attributes.size());
  for (Map.Entry<String, String> entry : attributes.entrySet()) {
    attributesList.add(
        CustomAttribute.builder().setKey(entry.getKey()).setValue(entry.getValue()).build());
  }

  // Sort by key
  Collections.sort(
      attributesList,
      (CustomAttribute attr1, CustomAttribute attr2) -> attr1.getKey().compareTo(attr2.getKey()));

  return attributesList;
}
 
Example 3
Source File: SearchEngine.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves tracks matching the given query from the database.
 *
 * @param query the query to retrieve for
 * @param tracks list to fill with the resulting tracks
 */
private void retrieveTracks(SearchQuery query, ArrayList<Track> tracks) {
  String queryLikeSelection = "%" + query.textQuery + "%";
  String[] trackSelectionArgs = new String[] {
      queryLikeSelection,
      queryLikeSelection,
      queryLikeSelection };

  Cursor cursor = null;
  try {
    cursor = providerUtils.getTrackCursor(
        TRACK_SELECTION_QUERY, trackSelectionArgs, TRACK_SELECTION_ORDER);
    if (cursor != null) {
      tracks.ensureCapacity(cursor.getCount());
      while (cursor.moveToNext()) {
        tracks.add(providerUtils.createTrack(cursor));
      }
    }
  } finally {
    if (cursor != null) {
      cursor.close();
    }
  }
}
 
Example 4
Source File: RestartPipelinedRegionStrategy.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private void makeAllOneRegion(List<ExecutionJobVertex> jobVertices) {
	LOG.warn("Cannot decompose ExecutionGraph into individual failover regions due to use of " +
			"Co-Location constraints (iterations). Job will fail over as one holistic unit.");

	final ArrayList<ExecutionVertex> allVertices = new ArrayList<>();

	for (ExecutionJobVertex ejv : jobVertices) {

		// safe some incremental size growing
		allVertices.ensureCapacity(allVertices.size() + ejv.getParallelism());

		allVertices.addAll(Arrays.asList(ejv.getTaskVertices()));
	}

	final FailoverRegion singleRegion = createFailoverRegion(executionGraph, allVertices);
	for (ExecutionVertex ev : allVertices) {
		vertexToRegion.put(ev, singleRegion);
	}
}
 
Example 5
Source File: CrashlyticsReportPersistence.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * @return finalized (no longer changing) Crashlytics Reports, sorted first from high to low
 *     priority, secondarily sorted from most recent to least
 */
@NonNull
public List<CrashlyticsReportWithSessionId> loadFinalizedReports() {
  final List<File> allReportFiles = getAllFinalizedReportFiles();
  final ArrayList<CrashlyticsReportWithSessionId> allReports = new ArrayList<>();
  allReports.ensureCapacity(allReportFiles.size());
  for (File reportFile : getAllFinalizedReportFiles()) {
    try {
      CrashlyticsReport jsonReport = TRANSFORM.reportFromJson(readTextFile(reportFile));
      allReports.add(CrashlyticsReportWithSessionId.create(jsonReport, reportFile.getName()));
    } catch (IOException e) {
      Logger.getLogger().d("Could not load report file " + reportFile + "; deleting", e);
      reportFile.delete();
    }
  }
  return allReports;
}
 
Example 6
Source File: ActivityTemplates.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
public static String linkObjects(String firstObjectName, String secondObjectName, String associationName,
		Optional<String> endPoint1, String endPoint2, LinkFunctionType linkType) {
	
	/*String secondTemplateArgument = "typename " + associationName + "::" + endPoint2;

	if(linkType == LinkFunctionType.DelegeateConnect) {
		secondTemplateArgument = endPoint2;
	}*/
	ArrayList<String> parameters = new ArrayList<>();
	parameters.add(firstObjectName);
	parameters.add(roleReadFromAssoc(associationName, endPoint2));
	parameters.add(secondObjectName);
	
	if(endPoint1.isPresent()) {
		parameters.ensureCapacity(4);
		parameters.add(0, roleReadFromAssoc(associationName, endPoint1.get()));
	}
	return blockStatement(operationCall(LinkTemplates.getLinkFunctionName(linkType),parameters));

}
 
Example 7
Source File: ValueList.java    From BigDataScript with Apache License 2.0 6 votes vote down vote up
public void setValue(long idx, Value value) {
	ArrayList<Value> list = (ArrayList<Value>) this.list;

	int iidx = (int) idx;
	if (idx < 0) throw new RuntimeException("Cannot set list element indexed with negative index value: " + idx);

	// Make sure the array is big enough to hold the data
	if (iidx >= list.size()) {
		list.ensureCapacity(iidx + 1);
		Type elemType = ((TypeList) type).getElementType();
		while (list.size() <= iidx)
			list.add(elemType.newDefaultValue());
	}

	list.set((int) idx, value);
}
 
Example 8
Source File: ArrayListTest.java    From jtransc with Apache License 2.0 6 votes vote down vote up
static public void arrayListTest() {
	ArrayList<String> list = new ArrayList<String>();
	StringBuilder sb = new StringBuilder();

	JTranscConsole.log(list.size());
	sb.append(list.size());
	list.add("A");
	JTranscConsole.log("------------");
	JTranscConsole.log(list.size());
	sb.append(list.get(0));
	sb.append(list.size());
	list.add("B");
	list.add("C");
	sb.append(list.size());
	list.ensureCapacity(5);
	sb.append(list.size());
	list.trimToSize();
	sb.append(list.size());

	Collections.reverse(list);
	for (String item : list) sb.append(item);

	System.out.println("ArrayList:" + sb.toString());
}
 
Example 9
Source File: EnsureCapacity.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testArrayList() {
    ArrayList<String> al = new ArrayList<String>();
    al.add("abc");
    al.ensureCapacity(Integer.MIN_VALUE);

    // there is no method to query the capacity of ArrayList
    // so before and after capacity are not checked
}
 
Example 10
Source File: EnsureCapacity.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void testArrayList() {
    ArrayList<String> al = new ArrayList<String>();
    al.add("abc");
    al.ensureCapacity(Integer.MIN_VALUE);

    // there is no method to query the capacity of ArrayList
    // so before and after capacity are not checked
}
 
Example 11
Source File: EnsureCapacity.java    From native-obfuscator with GNU General Public License v3.0 5 votes vote down vote up
private static void testArrayList() {
    ArrayList<String> al = new ArrayList<String>();
    al.add("abc");
    al.ensureCapacity(Integer.MIN_VALUE);

    // there is no method to query the capacity of ArrayList
    // so before and after capacity are not checked
}
 
Example 12
Source File: Field.java    From cfr with MIT License 5 votes vote down vote up
public Field(ByteData raw, final ConstantPool cp, final ClassFileVersion classFileVersion) {
    this.cp = cp;
    this.accessFlags = AccessFlag.build(raw.getU2At(OFFSET_OF_ACCESS_FLAGS));
    int attributes_count = raw.getU2At(OFFSET_OF_ATTRIBUTES_COUNT);
    ArrayList<Attribute> tmpAttributes = new ArrayList<Attribute>();
    tmpAttributes.ensureCapacity(attributes_count);
    long attributesLength = ContiguousEntityFactory.build(raw.getOffsetData(OFFSET_OF_ATTRIBUTES), attributes_count, tmpAttributes,
            AttributeFactory.getBuilder(cp, classFileVersion));

    this.attributes = new AttributeMap(tmpAttributes);
    AccessFlag.applyAttributes(attributes, accessFlags);
    this.descriptorIndex = raw.getU2At(OFFSET_OF_DESCRIPTOR_INDEX);
    int nameIndex = raw.getU2At(OFFSET_OF_NAME_INDEX);
    this.length = OFFSET_OF_ATTRIBUTES + attributesLength;
    AttributeConstantValue cvAttribute = attributes.getByName(AttributeConstantValue.ATTRIBUTE_NAME);
    this.fieldName = cp.getUTF8Entry(nameIndex).getValue();
    this.disambiguate = false;
    TypedLiteral constValue = null;
    if (cvAttribute != null) {
        constValue = TypedLiteral.getConstantPoolEntry(cp, ((AttributeConstantValue) cvAttribute).getValue());
        if (constValue.getType() == TypedLiteral.LiteralType.Integer) {
            // Need to check if the field is actually something smaller than an integer, and downcast the
            // literal - sufficiently constructed to do this. (although naughty).
            JavaTypeInstance thisType = getJavaTypeInstance();
            if (thisType instanceof RawJavaType) {
                constValue = TypedLiteral.shrinkTo(constValue, (RawJavaType)thisType);
            }
        }
    }
    this.constantValue = constValue;
}
 
Example 13
Source File: InternalThreadLocalMap.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <E> ArrayList<E> arrayList(int minCapacity) {
    ArrayList<E> list = (ArrayList<E>) arrayList;
    if (list == null) {
        arrayList = new ArrayList<Object>(minCapacity);
        return (ArrayList<E>) arrayList;
    }
    list.clear();
    list.ensureCapacity(minCapacity);
    return list;
}
 
Example 14
Source File: TreeNode.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private <Y> void collectChildren(ArrayList<TreeNode<Y>> array) {
    List<TreeNode> c = this.getChildren();
    int size = c.size();
    array.ensureCapacity(array.size() + size);
    for (int i = 0; i < size; i++) {
        TreeNode<Y> next = c.get(i);
        array.add(next);
        next.collectChildren(array);
    }
}
 
Example 15
Source File: EnsureCapacity.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testArrayList() {
    ArrayList<String> al = new ArrayList<String>();
    al.add("abc");
    al.ensureCapacity(Integer.MIN_VALUE);

    // there is no method to query the capacity of ArrayList
    // so before and after capacity are not checked
}
 
Example 16
Source File: EnsureCapacity.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void testArrayList() {
    ArrayList<String> al = new ArrayList<String>();
    al.add("abc");
    al.ensureCapacity(Integer.MIN_VALUE);

    // there is no method to query the capacity of ArrayList
    // so before and after capacity are not checked
}
 
Example 17
Source File: DataDstLua.java    From xresloader with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void writeData(StringBuffer sb, Object data, int ident_num) {
    // null
    if (null == data) {
        sb.append("nil");
        return;
    }

    // 数字
    // 枚举值已被转为Java Long,会在这里执行
    if (data instanceof Number) {
        sb.append(data.toString());
        return;
    }

    // 布尔
    if (data instanceof Boolean) {
        sb.append(((Boolean) data) ? "true" : "false");
        return;
    }

    // 字符串&二进制
    if (data instanceof String) {
        // 利用json的字符串格式,和lua一样的没必要再引入一个库
        sb.append(JSONObject.quote((String) data));
        return;
    }

    // 列表
    if (data instanceof List) {
        List<Object> ls = (List<Object>) data;
        sb.append("{").append(endl);

        for (Object obj : ls) {
            writeIdent(sb, ident_num + 1);
            writeData(sb, obj, ident_num + 1);
            sb.append(",").append(endl);
        }

        writeIdent(sb, ident_num);
        sb.append("}");
        return;
    }

    // Hashmap
    if (data instanceof Map<?, ?>) {
        Map<?, ?> mp = (Map<?, ?>) data;
        sb.append("{").append(endl);

        ArrayList<Map.Entry<?, ?>> sorted_array = new ArrayList<Map.Entry<?, ?>>();
        sorted_array.ensureCapacity(mp.size());
        sorted_array.addAll(mp.entrySet());
        sorted_array.sort((l, r) -> {
            if (l.getValue() instanceof Integer && r.getValue() instanceof Integer) {
                return ((Integer) l.getValue()).compareTo((Integer) r.getValue());
            }

            if (l.getKey() instanceof Integer && r.getKey() instanceof Integer) {
                return ((Integer) l.getKey()).compareTo((Integer) r.getKey());
            } else if (l.getKey() instanceof Long && r.getKey() instanceof Long) {
                return ((Long) l.getKey()).compareTo((Long) r.getKey());
            } else {
                return l.getKey().toString().compareTo(r.getKey().toString());
            }
        });
        for (Map.Entry<?, ?> item : sorted_array) {
            writeIdent(sb, ident_num + 1);
            if (data instanceof SpecialInnerHashMap<?, ?>) {
                if (item.getKey() instanceof String) {
                    sb.append("[");
                    sb.append(JSONObject.quote((String) item.getKey())).append("] = ");
                } else {
                    sb.append("[");
                    sb.append(item.getKey()).append("] = ");
                }
            } else {
                sb.append(item.getKey()).append(" = ");
            }

            writeData(sb, item.getValue(), ident_num + 1);
            sb.append(",").append(endl);
        }

        writeIdent(sb, ident_num);
        sb.append("}");
        return;
    }

    sb.append(JSONObject.quote(data.toString()));
}
 
Example 18
Source File: DataDstUECsv.java    From xresloader with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void writeConstData(CSVPrinter sp, Object data, String prefix) throws IOException {
    // null
    if (null == data) {
        sp.printRecord(prefix, "");
        return;
    }

    // 数字
    // 枚举值已被转为Java Long,会在这里执行
    if (data instanceof Number) {
        sp.printRecord(prefix, data);
        return;
    }

    // 布尔
    if (data instanceof Boolean) {
        sp.printRecord(prefix, ((Boolean) data) ? 1 : 0);
        return;
    }

    // 字符串&二进制
    if (data instanceof String) {
        sp.printRecord(prefix, data);
        return;
    }

    // 列表
    if (data instanceof List) {
        List<Object> ls = (List<Object>) data;
        for (int i = 0; i < ls.size(); ++i) {
            if (prefix.isEmpty()) {
                writeConstData(sp, ls.get(i), String.format("%d", i));
            } else {
                writeConstData(sp, ls.get(i), String.format("%s.%d", prefix, i));
            }
        }
        return;
    }

    // Hashmap
    if (data instanceof Map) {
        Map<String, Object> mp = (Map<String, Object>) data;
        ArrayList<Map.Entry<String, Object>> sorted_array = new ArrayList<Map.Entry<String, Object>>();
        sorted_array.ensureCapacity(mp.size());
        sorted_array.addAll(mp.entrySet());
        sorted_array.sort((l, r) -> {
            if (l.getValue() instanceof Integer && r.getValue() instanceof Integer) {
                return ((Integer) l.getValue()).compareTo((Integer) r.getValue());
            }

            return l.getKey().compareTo(r.getKey());
        });

        for (Map.Entry<String, Object> item : sorted_array) {
            if (prefix.isEmpty()) {
                writeConstData(sp, item.getValue(), String.format("%s", item.getKey()));
            } else {
                writeConstData(sp, item.getValue(), String.format("%s.%s", prefix, item.getKey()));
            }
        }
        return;
    }

    sp.printRecord(prefix, data.toString());
}
 
Example 19
Source File: NettyConnection.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
public final void fireReady(final boolean ready) {
   ArrayList<ReadyListener> readyToCall = localListenersPool.get();
   if (readyToCall != null) {
      localListenersPool.set(null);
   }
   synchronized (readyListeners) {
      this.ready = ready;

      if (ready) {
         final int size = this.readyListeners.size();
         if (readyToCall != null) {
            readyToCall.ensureCapacity(size);
         }
         try {
            for (int i = 0; i < size; i++) {
               final ReadyListener readyListener = readyListeners.get(i);
               if (readyListener == null) {
                  break;
               }
               if (readyToCall == null) {
                  readyToCall = new ArrayList<>(size);
               }
               readyToCall.add(readyListener);
            }
         } finally {
            readyListeners.clear();
         }
      }
   }
   if (readyToCall != null) {
      try {
         readyToCall.forEach(readyListener -> {
            try {
               readyListener.readyForWriting();
            } catch (Throwable logOnly) {
               ActiveMQClientLogger.LOGGER.failedToSetChannelReadyForWriting(logOnly);
            }
         });
      } catch (Throwable t) {
         ActiveMQClientLogger.LOGGER.failedToSetChannelReadyForWriting(t);
      } finally {
         readyToCall.clear();
         if (localListenersPool.get() != null) {
            localListenersPool.set(readyToCall);
         }
      }
   }
}
 
Example 20
Source File: SpillingBuffer.java    From Flink-CEPplus with Apache License 2.0 3 votes vote down vote up
/**
 * Utility method that moves elements. It avoids copying the data into a dedicated array first, as
 * the {@link ArrayList#addAll(java.util.Collection)} method does.
 * 
 * @param <E>
 * @param source
 * @param target
 */
private static final <E> void moveAll(ArrayList<E> source, ArrayList<E> target) {
	target.ensureCapacity(target.size() + source.size());
	for (int i = source.size() - 1; i >= 0; i--) {
		target.add(source.remove(i));
	}
}