java.util.ArrayList#set ( )源码实例Demo

下面列出了java.util.ArrayList#set ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: systemsgenetics   文件: MergeDoubleMatrices.java
/**
 * Merge a set of matrices based on row identifiers. Automatic skypping of
 * errors merges.
 *
 * @param matrixI
 * @param matrixII
 * @param removeOldMatrix
 * @return
 */
public static DoubleMatrixDataset<String, String> combineBasedOnRows(ArrayList<DoubleMatrixDataset<String, String>> datasets) {
    DoubleMatrixDataset<String, String> newMatrix = datasets.get(0);
    datasets.set(0, null);
    if (datasets.size() > 1) {
        ProgressBar pb = new ProgressBar(datasets.size());
        for (int i = 1; i < datasets.size(); ++i) {
            try {
                newMatrix = mergeMatrixBasedOnRows(newMatrix, datasets.get(i), false);
            } catch (Exception ex) {
                Logger.getLogger(MergeDoubleMatrices.class.getName()).log(Level.SEVERE, null, ex);
            }
            datasets.set(i, null);
            pb.iterate();
        }
        pb.close();
    }

    return (newMatrix);
}
 
源代码2 项目: HeavenMS   文件: InventorySortHandler.java
private void PartitionByQuantity(int Esq, int Dir, ArrayList<Item> A) {
    Item x, w;

    i = Esq;
    j = Dir;
    
    x = A.get((i + j) / 2);
    do {
        while (x.getQuantity() > A.get(i).getQuantity()) i++;
        while (x.getQuantity() < A.get(j).getQuantity()) j--;
        
        if (i <= j) {
            w = A.get(i);
            A.set(i, A.get(j));
            A.set(j, w);

            i++;
            j--;
        }
    } while (i <= j);
}
 
@Test
public void TestNullGeom() throws Exception {
       ArrayList<Object> stuff = new ArrayList<Object>();
	Properties proptab = new Properties();
	proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "shape");
	proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "binary");
	AbstractSerDe jserde = mkSerDe(proptab);
       StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector();

       //value.set("{\"properties\":{},\"geometry\":{\"type\":\"Point\",\"coordinates\":[15.0,5.0]}}");
       addWritable(stuff, new Point(15.0, 5.0));
	Object row = runSerDe(stuff, jserde, rowOI);
	Object fieldData = getField("shape", row, rowOI);
	ckPoint(new Point(15.0, 5.0), (BytesWritable)fieldData);

       //value.set("{\"properties\":{},\"coordinates\":null}");
	stuff.set(0, null);
	row = runSerDe(stuff, jserde, rowOI);
	fieldData = getField("shape", row, rowOI);
	Assert.assertNull(fieldData);
}
 
源代码4 项目: HeavenMS   文件: MapleStorageInventory.java
private void PartitionByName(int Esq, int Dir, ArrayList<Item> A) {
    Item x, w;

    i = Esq;
    j = Dir;
    
    x = A.get((i + j) / 2);
    do {
        while (ii.getName(x.getItemId()).compareTo(ii.getName(A.get(i).getItemId())) > 0) i++;
        while (ii.getName(x.getItemId()).compareTo(ii.getName(A.get(j).getItemId())) < 0) j--;
        
        if (i <= j) {
            w = A.get(i);
            A.set(i, A.get(j));
            A.set(j, w);

            i++;
            j--;
        }
    } while (i <= j);
}
 
源代码5 项目: gemfirexd-oss   文件: SURQueryMixTest.java
/**
 * Create a random sample of rows
 * @param rows Map to create sample from
 * @param k number of rows in the sample
 * @return a list containing k elements of rows
 **/
private List createRandomSample(final Map rows, int k) {
    Random r = new Random();
    ArrayList sampledKeys = new ArrayList();
    int n = 0;        
    for (Iterator i = rows.keySet().iterator(); i.hasNext();) {
        Object key = i.next();
        n++;            
        if (n<=k) {
            sampledKeys.add(key);
        } else {
            // sampledKeys now has a size of k
            double d = r.nextDouble();
            // p = probability of going into the sample
            double p = (double) k / (double) n; 
            if (d<p) {
                // Replace a random value from the sample with the new value
                int keyToReplace = Math.abs(r.nextInt())%k;                    
                sampledKeys.set(keyToReplace, key);
            }
        }
    }
    return sampledKeys;
}
 
源代码6 项目: Math-Game   文件: TypeManager.java
/**
 * @return A randomly generated ArrayList of decimals
 */
public ArrayList<Double> randomDecimalValues() {
	Random generator = new Random();

	ArrayList<Double> cardValues = new ArrayList<Double>();

	for (int x = 0; x < 6; x++) {
		int temp = (int)(generator.nextDouble()*100);
		cardValues.add( temp/100.0 ); //TODO Fix random decimal generation
	}
	
	int RandomInsert1 = (int)(generator.nextFloat() * 6);
	int RandomInsert2 = (int)(generator.nextFloat() * 6);
	while (RandomInsert2 == RandomInsert1) {
		RandomInsert2 = (int)(generator.nextFloat() * 6);
	}

	cardValues.set(RandomInsert1, Double.valueOf(sql.getNum1()));
	cardValues.set(RandomInsert2, Double.valueOf(sql.getNum2()));

	return cardValues;
}
 
源代码7 项目: besu   文件: BranchNode.java
public Node<V> replaceChild(final byte index, final Node<V> updatedChild) {
  final ArrayList<Node<V>> newChildren = new ArrayList<>(children);
  newChildren.set(index, updatedChild);

  if (updatedChild == NULL_NODE) {
    if (value.isPresent() && !hasChildren()) {
      return nodeFactory.createLeaf(Bytes.of(index), value.get());
    } else if (!value.isPresent()) {
      final Optional<Node<V>> flattened = maybeFlatten(newChildren);
      if (flattened.isPresent()) {
        return flattened.get();
      }
    }
  }

  return nodeFactory.createBranch(newChildren, value);
}
 
源代码8 项目: OSPREY3   文件: KSConfigFileParser.java
public ArrayList<String> getWTSequence() {

		Molecule m = new Strand.Builder(PDBIO.readFile(params.getFile("PDBNAME"))).build().mol;
		ArrayList<String> flexibleRes = getFlexRes();
		int numPos = flexibleRes.size();
		ArrayList<String> wt = new ArrayList<>(); for( int pos = 0; pos < numPos; ++pos ) wt.add(null);

		for(int pos=0; pos<numPos; pos++) {
			Residue res = m.getResByPDBResNumber( flexibleRes.get(pos) );
			String wtName = res.template.name;
			wt.set(pos, wtName);
		}

		wt.trimToSize();
		return wt;
	}
 
源代码9 项目: systemds   文件: CPlanOpRewriter.java
public CNodeTpl simplifyCPlan(CNodeTpl tpl) {
	//apply template specific rewrites
	tpl = rewriteRemoveOuterNeq0(tpl); // Outer(a!=0) -> Outer(1)
	
	//apply operation specific rewrites
	if( tpl instanceof CNodeMultiAgg ) {
		ArrayList<CNode> outputs = ((CNodeMultiAgg)tpl).getOutputs();
		for( int i=0; i< outputs.size(); i++ )
			outputs.set(i, rSimplifyCNode(outputs.get(i)));
	}
	else {
		tpl.setOutput(rSimplifyCNode(tpl.getOutput()));
	}
	
	return tpl;
}
 
源代码10 项目: openboard   文件: PointerTrackerQueue.java
public void add(final Element pointer) {
    synchronized (mExpandableArrayOfActivePointers) {
        if (DEBUG) {
            Log.d(TAG, "add: " + pointer + " " + this);
        }
        final ArrayList<Element> expandableArray = mExpandableArrayOfActivePointers;
        final int arraySize = mArraySize;
        if (arraySize < expandableArray.size()) {
            expandableArray.set(arraySize, pointer);
        } else {
            expandableArray.add(pointer);
        }
        mArraySize = arraySize + 1;
    }
}
 
源代码11 项目: 4pdaClient-plus   文件: AppsListFragment.java
private void compareFromMatcher(ArrayList<String> appsName, ArrayList<AppItem> apps, Matcher m) {
    while (m.find()) {
        String id = m.group(1);
        AppItem app;
        while ((app = findById(apps, id)) != null) {
            if (isCancelled())
                return;
            app.Ids.clear();
            app.setId(id);
            app.setDescription(Html.fromHtml(m.group(3)));
            app.setFindedState(AppItem.STATE_NORMAL);
        }

        String normTitle = normalizeTitle(m.group(2));
        for (int i = 0; i < appsName.size(); i++) {
            if (isCancelled())
                return;
            if (normTitle.equals(appsName.get(i))) {
                app = apps.get(i);
                app.Ids.clear();
                app.setId(id);
                app.setDescription(Html.fromHtml(m.group(3)));
                app.setFindedState(AppItem.STATE_NORMAL);

                appsName.set(i, null);

            }
        }
    }
}
 
/**
 * Done parsing.
 *
 * @throws SAXException if there is a parsing error.
 */
protected void doneParsing() throws SAXException {
  super.doneParsing();
  final Properties properties = getResult();
  final ArrayList list = new ArrayList();
  final Iterator entries = properties.entrySet().iterator();
  while ( entries.hasNext() ) {
    final Map.Entry o = (Map.Entry) entries.next();
    final String key = (String) o.getKey();
    final String value = (String) o.getValue();
    try {
      int index = Integer.parseInt( key );
      if ( index < 0 ) {
        throw new ParseException( "Failed to parse array index", getLocator() );
      }

      list.ensureCapacity( index );
      while ( list.size() < ( index + 1 ) ) {
        list.add( null );
      }
      list.set( index, ObjectConverterFactory.convert( componentType, value, getLocator() ) );
    } catch ( NumberFormatException nfe ) {
      throw new ParseException( "Failed to parse array index", getLocator() );
    }
  }
  retval = list.toArray();
}
 
源代码13 项目: OpenLibre   文件: ReadingData.java
private void shiftAgeToMatchPreviousReadings(Realm realmProcessedData, ArrayList<Integer> glucoseLevels, ArrayList<Integer> ageInSensorMinutesList) {
    // lookup previous data points from the same sensor and age
    RealmResults<GlucoseData> previousGlucoseDataList = realmProcessedData.where(GlucoseData.class)
            .contains(GlucoseData.ID, sensor.getTagId())
            .equalTo(GlucoseData.IS_TREND_DATA, false)
            .greaterThanOrEqualTo(GlucoseData.AGE_IN_SENSOR_MINUTES, ageInSensorMinutesList.get(0))
            .lessThanOrEqualTo(GlucoseData.AGE_IN_SENSOR_MINUTES, ageInSensorMinutesList.get(ageInSensorMinutesList.size() - 1))
            .findAllSorted(GlucoseData.AGE_IN_SENSOR_MINUTES, Sort.ASCENDING);

    // if there are enough previous and new data points, try to fit them together
    // this is needed as the exact time when a new history value is generated is not known
    // therefore it can happen, that the same data point from two readings would be mapped to different dates
    if (previousGlucoseDataList.size() > 3 && glucoseLevels.size() > 3) {
        int shift = 0;
        boolean equal = listsStartEqual(glucoseLevels, previousGlucoseDataList);
        if (!equal) {
            shift = -1;
            equal = listsStartEqual(glucoseLevels.subList(1, glucoseLevels.size()), previousGlucoseDataList);
            if (!equal) {
                shift = 1;
                equal = listsStartEqual(glucoseLevels, previousGlucoseDataList.subList(1, previousGlucoseDataList.size()));
            }
        }
        // if a match between previous and new data points was found, shift the age of the new data points to fit the previous ones
        if (equal) {
            if (shift != 0) {
                for (int c = 0; c < ageInSensorMinutesList.size(); c++) {
                    ageInSensorMinutesList.set(c, ageInSensorMinutesList.get(c) + shift * historyIntervalInMinutes);
                }
            }
        } else {
            throw new RuntimeException("No match found between old and new data points.");
        }
    }
}
 
源代码14 项目: xDrip   文件: BaseWatchFace.java
public void addDataMapTreats(DataMap dataMap, ArrayList<BgWatchData> dataList) {//KS
    double sgv = dataMap.getDouble("sgvDouble");
    double high = dataMap.getDouble("high");//carbs
    double low = dataMap.getDouble("low");//insulin
    double timestamp = dataMap.getDouble("timestamp");

     if (d) Log.d(TAG, "addDataMapTreats entry=" + dataMap);

    final int size = (dataList != null ? dataList.size() : 0);
    BgWatchData bgdata = new BgWatchData(sgv, high, low, timestamp);
    if (d) Log.d(TAG, "addDataMapTreats bgdata.sgv=" + bgdata.sgv + " bgdata.carbs=" + bgdata.high  + " bgdata.insulin=" + bgdata.low + " bgdata.timestamp=" + bgdata.timestamp + " timestamp=" + JoH.dateTimeText((long)bgdata.timestamp));
    if (size > 0) {
        if (dataList.contains(bgdata)) {
            int i = dataList.indexOf(bgdata);
            if (d) {
                BgWatchData data = dataList.get(dataList.indexOf(bgdata));
                Log.d(TAG, "addDataMapTreats replace indexOf=" + i + " treatsDataList.carbs=" + data.high + " treatsDataList.insulin=" + data.low + " treatsDataList.timestamp=" + data.timestamp);
            }
            dataList.set(i, bgdata);
        } else {
            if (d) Log.d(TAG, "addDataMapTreats add " + " treatsDataList.carbs=" + bgdata.high  + " treatsDataList.insulin=" + bgdata.low + " entry.timestamp=" + bgdata.timestamp);
            dataList.add(bgdata);
        }
    }
    else {
        dataList.add(bgdata);
    }
     if (d) Log.d(TAG, "addDataMapTreats dataList.size()=" + dataList.size());
}
 
源代码15 项目: jdk8u-dev-jdk   文件: LengthCheckTest.java
@Override
public void execTest() throws Exception {
    boolean gotException = false;
    SSLEngineResult clientResult;   // results from client's last op
    SSLEngineResult serverResult;   // results from server's last op

    log("\n==== Test: Client receives 64-byte session ID ====");

    // Send Client Hello
    clientResult = clientEngine.wrap(clientOut, cTOs);
    log("client wrap: ", clientResult);
    runDelegatedTasks(clientResult, clientEngine);
    cTOs.flip();
    dumpByteBuffer("CLIENT-TO-SERVER", cTOs);

    // Server consumes Client Hello
    serverResult = serverEngine.unwrap(cTOs, serverIn);
    log("server unwrap: ", serverResult);
    runDelegatedTasks(serverResult, serverEngine);
    cTOs.compact();

    // Server generates ServerHello/Cert/Done record
    serverResult = serverEngine.wrap(serverOut, sTOc);
    log("server wrap: ", serverResult);
    runDelegatedTasks(serverResult, serverEngine);
    sTOc.flip();

    // Intercept the ServerHello messages and instead send
    // one that has a 64-byte session ID.
    if (isTlsMessage(sTOc, TLS_RECTYPE_HANDSHAKE,
                TLS_HS_SERVER_HELLO)) {
        ArrayList<ByteBuffer> recList = splitRecord(sTOc);

        // Use the original ServerHello as a template to craft one
        // with a longer-than-allowed session ID.
        ByteBuffer servHelloBuf =
                createEvilServerHello(recList.get(0), 64);

        recList.set(0, servHelloBuf);

        // Now send each ByteBuffer (each being a complete
        // TLS record) into the client-side unwrap.
        for (ByteBuffer bBuf : recList) {
            dumpByteBuffer("SERVER-TO-CLIENT", bBuf);
            try {
                clientResult = clientEngine.unwrap(bBuf, clientIn);
            } catch (SSLProtocolException e) {
                log("Received expected SSLProtocolException: " + e);
                gotException = true;
            }
            log("client unwrap: ", clientResult);
            runDelegatedTasks(clientResult, clientEngine);
        }
    } else {
        dumpByteBuffer("SERVER-TO-CLIENT", sTOc);
        log("client unwrap: ", clientResult);
        runDelegatedTasks(clientResult, clientEngine);
    }
    sTOc.compact();

    // The Client should now send a TLS Alert
    clientResult = clientEngine.wrap(clientOut, cTOs);
    log("client wrap: ", clientResult);
    runDelegatedTasks(clientResult, clientEngine);
    cTOs.flip();
    dumpByteBuffer("CLIENT-TO-SERVER", cTOs);

    // At this point we can verify that both an exception
    // was thrown and the proper action (a TLS alert) was
    // sent back to the server.
    if (gotException == false ||
        !isTlsMessage(cTOs, TLS_RECTYPE_ALERT, TLS_ALERT_LVL_FATAL,
                TLS_ALERT_INTERNAL_ERROR)) {
        throw new SSLException(
            "Client failed to throw Alert:fatal:internal_error");
    }
}
 
源代码16 项目: astor   文件: HtmlTreeBuilder.java
private void replaceInQueue(ArrayList<Element> queue, Element out, Element in) {
    int i = queue.lastIndexOf(out);
    Validate.isTrue(i != -1);
    queue.set(i, in);
}
 
源代码17 项目: gravel   文件: OrderedCollectionExtensions.java
public static Object at_put_(ArrayList receiver, int index, Object value) {
	receiver.set(index - 1, value);
	return value;
}
 
源代码18 项目: j2objc   文件: ConcurrentSkipListMap.java
/**
 * 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<>();

    // 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;
}
 
源代码19 项目: tsml   文件: FastShapelets.java
Shapelet findBestSAX(int top_k) {
    //init the ArrayList with nulls.
    ArrayList<Pair<Integer, Double>> Dist = new ArrayList<>();
    for (int i = 0; i < numObj; i++) {
        Dist.add(null);
    }

    int word;
    double gain, dist_th, gap;
    int q_obj, q_pos;
    USAX_elm_type usax;
    int label, kk, total_c_in, num_diff;

    Shapelet sh = new Shapelet(), bsf_sh = new Shapelet();

    if (top_k > 0) {
        Collections.sort(scoreList, new ScoreComparator());
    }
    top_k = Math.abs(top_k);

    for (int k = 0; k < Math.min(top_k, scoreList.size()); k++) {
        word = scoreList.get(k).first;
        usax = uSAXMap.get(word);
        for (kk = 0; kk < Math.min(usax.sax_id.size(), 1); kk++) {
            int[] c_in = new int[numClass];
            int[] c_out = new int[numClass];
            //init the array list with 0s
            double[] query = new double[subseqLength];

            q_obj = usax.sax_id.get(kk).first;
            q_pos = usax.sax_id.get(kk).second;

            for (int i = 0; i < numClass; i++) {
                c_in[i] = 0;
                c_out[i] = classFreq[i];
            }
            for (int i = 0; i < subseqLength; i++) {
                query[i] = data.get(q_obj).get(q_pos + i);
            }

            double dist;
            int m = query.length;
            double[] Q = new double[m];
            int[] order = new int[m];
            for (int obj = 0; obj < numObj; obj++) {
                dist = nn.nearestNeighborSearch(query, data.get(obj), obj, Q, order);
                Dist.set(obj, new Pair<>(obj, dist));
            }

            Collections.sort(Dist, new DistComparator());

            total_c_in = 0;
            for (int i = 0; i < Dist.size() - 1; i++) {
                Pair<Integer, Double> pair_i = Dist.get(i);
                Pair<Integer, Double> pair_ii = Dist.get(i + 1);

                dist_th = (pair_i.second + pair_ii.second) / 2.0;
                //gap = Dist[i+1].second - dist_th;
                gap = ((double) (pair_ii.second - dist_th)) / Math.sqrt(subseqLength);
                label = Label.get(pair_i.first);
                c_in[label]++;
                c_out[label]--;
                total_c_in++;
                num_diff = Math.abs(numObj - 2 * total_c_in);
                //gain = CalInfoGain1(c_in, c_out);
                gain = calcInfoGain2(c_in, c_out, total_c_in, numObj - total_c_in);

                sh.setValueFew(gain, gap, dist_th);
                if (bsf_sh.lessThan(sh)) {
                    bsf_sh.setValueAll(gain, gap, dist_th, q_obj, q_pos, subseqLength, num_diff, c_in, c_out);
                }
            }
        }
    }
    return bsf_sh;
}
 
源代码20 项目: openjdk-jdk8u-backup   文件: NameConverter.java
/**
 * Computes a Java package name from a namespace URI,
 * as specified in the spec.
 *
 * @return
 *      null if it fails to derive a package name.
 */
public String toPackageName( String nsUri ) {
    // remove scheme and :, if present
    // spec only requires us to remove 'http' and 'urn'...
    int idx = nsUri.indexOf(':');
    String scheme = "";
    if(idx>=0) {
        scheme = nsUri.substring(0,idx);
        if( scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("urn") )
            nsUri = nsUri.substring(idx+1);
    }

    // tokenize string
    ArrayList<String> tokens = tokenize( nsUri, "/: " );
    if( tokens.size() == 0 ) {
        return null;
    }

    // remove trailing file type, if necessary
    if( tokens.size() > 1 ) {
        // for uri's like "www.foo.com" and "foo.com", there is no trailing
        // file, so there's no need to look at the last '.' and substring
        // otherwise, we loose the "com" (which would be wrong)
        String lastToken = tokens.get( tokens.size()-1 );
        idx = lastToken.lastIndexOf( '.' );
        if( idx > 0 ) {
            lastToken = lastToken.substring( 0, idx );
            tokens.set( tokens.size()-1, lastToken );
        }
    }

    // tokenize domain name and reverse.  Also remove :port if it exists
    String domain = tokens.get( 0 );
    idx = domain.indexOf(':');
    if( idx >= 0) domain = domain.substring(0, idx);
    ArrayList<String> r = reverse( tokenize( domain, scheme.equals("urn")?".-":"." ) );
    if( r.get( r.size()-1 ).equalsIgnoreCase( "www" ) ) {
        // remove leading www
        r.remove( r.size()-1 );
    }

    // replace the domain name with tokenized items
    tokens.addAll( 1, r );
    tokens.remove( 0 );

    // iterate through the tokens and apply xml->java name algorithm
    for( int i = 0; i < tokens.size(); i++ ) {

        // get the token and remove illegal chars
        String token = tokens.get( i );
        token = removeIllegalIdentifierChars( token );

        // this will check for reserved keywords
        if (SourceVersion.isKeyword(token.toLowerCase())) {
            token = '_' + token;
        }

        tokens.set( i, token.toLowerCase() );
    }

    // concat all the pieces and return it
    return combine( tokens, '.' );
}