Java Code Examples for java.util.ArrayList.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: manifold   File: ExtensionManifoldTest.java   View Source Code Vote up 7 votes
protected void testCoverage( Class extensionClass ) {
  Method[] methods = extensionClass.getMethods();
  ArrayList<String> untested = new ArrayList<>();
  for (Method m : methods) {
    if (Modifier.isStatic(m.getModifiers()) && !Modifier.isPrivate(m.getModifiers())) {
      try {
        String name = m.getName();
        getClass().getMethod("test" + Character.toUpperCase(name.charAt(0)) + name.substring(1));
      } catch (Exception e) {
        String fullDesc = m.toString();
        untested.add( "Untested: " + fullDesc.substring( fullDesc.indexOf( '.' + m.getName() + '(' ) + 1 ) );
      }
    }
  }
  if (!untested.isEmpty()) {
    StringBuilder msg = new StringBuilder();
    untested.stream().sorted().forEach(e -> msg.append(e).append("\n"));
    msg.append("Expecting at least one test method per extension method of the form: testXxx().\n");
    TestCase.fail( msg.toString());
  }
}
 
Example 2
Project: Conjuga-Me-Java   File: Main.java   View Source Code Vote up 7 votes
private static ArrayList<Integer> interpretTime(String[] commands) throws InvalidDisplayOptionException{
  int indice = 0;
  ArrayList<Integer> actions = new ArrayList<Integer>(3);
  for(String command : commands){
    if (command.contains(Main.SINGLECOLUM) || command.contains(Main.DOUBLECOLUM) || command.contains(Main.TRIPLECOLUM))
      ;
    else if(command.contains(Main.INDICATIVO))
      actions.add(1);
    else if(command.contains(Main.CONJUNTIVO))
      actions.add(2);
    else if(command.contains(Main.IMPERATIVO))
      actions.add(3);
    else
      throw new InvalidDisplayOptionException(command);
  }
  if (actions.isEmpty()) {
    actions.add(1);
    actions.add(2);
    actions.add(3);
  }
  return actions;
}
 
Example 3
Project: monarch   File: TXRmtEvent.java   View Source Code Vote up 7 votes
public List getCreateEvents() {
  if (this.events == null) {
    return Collections.EMPTY_LIST;
  } else {
    ArrayList result = new ArrayList(this.events.size());
    Iterator it = this.events.iterator();
    while (it.hasNext()) {
      CacheEvent ce = (CacheEvent) it.next();
      if (ce.getOperation().isCreate() && isEventUserVisible(ce)) {
        result.add(ce);
      }
    }
    if (result.isEmpty()) {
      return Collections.EMPTY_LIST;
    } else {
      return Collections.unmodifiableList(result);
    }
  }
}
 
Example 4
Project: TPlayer   File: VPackageManagerService.java   View Source Code Vote up 6 votes
@Override
public VParceledListSlice<ProviderInfo> queryContentProviders(String processName, int vuid, int flags) {
    int userId = VUserHandle.getUserId(vuid);
    checkUserId(userId);
    flags = updateFlagsNought(flags);
    ArrayList<ProviderInfo> finalList = new ArrayList<>(3);
    // reader
    synchronized (mPackages) {
        for (VPackage.ProviderComponent p : mProvidersByComponent.values()) {
            PackageSetting ps = (PackageSetting) p.owner.mExtras;
            if (processName == null || ps.appId == VUserHandle.getAppId(vuid) && p.info.processName.equals(processName)) {
                ProviderInfo providerInfo = PackageParserEx.generateProviderInfo(p, flags, ps.readUserState(userId), userId);
                finalList.add(providerInfo);
            }
        }
    }
    if (!finalList.isEmpty()) {
        Collections.sort(finalList, sProviderInitOrderSorter);
    }
    return new VParceledListSlice<>(finalList);
}
 
Example 5
Project: Entrega-Final   File: Principal.java   View Source Code Vote up 6 votes
public boolean refreshList() throws DataSourceException {
    ArrayList<Produto> result = ServicoProduto.procurarProduto(ultimaPesquisa);        

    DefaultTableModel model = (DefaultTableModel) jtConsultar.getModel();

    model.setRowCount(0);
    
    if (result == null || result.isEmpty()) {
        return false;
    }

    for (int i = 0; i < result.size(); i++) {
        Produto p = result.get(i);
        if (p != null) {
            Object[] row = new Object[6];
            row[0] = p.getId();
            row[1] = p.getNome();
            row[2] = p.getCategoria();
            row[3] = p.getValorCompra();
            row[4] = p.getValorVenda();
            row[5] = p.getDtCadastro();
            model.addRow(row);
        }
    }
    return true;
}
 
Example 6
Project: Bridge   File: SaveActivity.java   View Source Code Vote up 6 votes
private boolean checkCrossUser() {
    Uri uri;
    if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
        uri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    } else {
        ArrayList<Uri> uris = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        uri = uris.isEmpty() ? null : uris.get(0);
    }

    if (uri != null && uri.getScheme().equals("file")) {
        String path = uri.getPath();
        if (!path.startsWith(Environment.getExternalStorageDirectory().getAbsolutePath())) {
            return false;
        }
    }
    return true;
}
 
Example 7
Project: KrGallery   File: MediaController.java   View Source Code Vote up 6 votes
public void removeLoadingFileObserver(FileDownloadProgressListener observer) {
    if (listenerInProgress) {
        deleteLaterArray.add(observer);
        return;
    }
    String fileName = observersByTag.get(observer.getObserverTag());
    if (fileName != null) {
        ArrayList<WeakReference<FileDownloadProgressListener>> arrayList = loadingFileObservers
                .get(fileName);
        if (arrayList != null) {
            for (int a = 0; a < arrayList.size(); a++) {
                WeakReference<FileDownloadProgressListener> reference = arrayList.get(a);
                if (reference.get() == null || reference.get() == observer) {
                    arrayList.remove(a);
                    a--;
                }
            }
            if (arrayList.isEmpty()) {
                loadingFileObservers.remove(fileName);
            }
        }
        observersByTag.remove(observer.getObserverTag());
    }
}
 
Example 8
Project: PlusGram   File: RecyclerView.java   View Source Code Vote up 5 votes
public ViewHolder getRecycledView(int viewType) {
    final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
    if (scrapHeap != null && !scrapHeap.isEmpty()) {
        final int index = scrapHeap.size() - 1;
        final ViewHolder scrap = scrapHeap.get(index);
        scrapHeap.remove(index);
        return scrap;
    }
    return null;
}
 
Example 9
Project: Sempala   File: ImpalaBase.java   View Source Code Vote up 5 votes
protected String toArgumentList(ArrayList<String> list) {
	if(list == null || list.isEmpty()) return null;
	String argList = "";
	if(list.size() == 1) return list.get(0);
	else {
		argList += "(" + list.get(0);
		for (int i=1; i<list.size(); i++) {
			argList += ", " + list.get(i);
		}
		argList += ")";
	}
	return argList;
}
 
Example 10
Project: incubator-netbeans   File: ProxyHighlightsContainer.java   View Source Code Vote up 5 votes
private AttributeSet findAttributes() {
    ArrayList<AttributeSet> list = new ArrayList<AttributeSet>();

    for(int i = 0; i < marks.length; i++) {
        if (marks[i].getPreviousMarkAttributes() != null) {
            list.add(marks[i].getPreviousMarkAttributes());
        }
    }

    if (!list.isEmpty()) {
        return AttributesUtilities.createComposite(list.toArray(new AttributeSet[list.size()]));
    } else {
        return null;
    }
}
 
Example 11
Project: zerocell   File: EntityHandler.java   View Source Code Vote up 5 votes
private ColumnMapping readColumnInfoViaReflection(Class<?> clazz) {
    Field[] fieldArray = clazz.getDeclaredFields();
    ArrayList<ColumnInfo> list = new ArrayList<>(fieldArray.length);
    ColumnInfo rowNumberColumn = null;
    for (Field field: fieldArray) {

        RowNumber rowNumberAnnotation = field.getAnnotation(RowNumber.class);

        if (! Objects.isNull(rowNumberAnnotation)) {
            rowNumberColumn = new ColumnInfo("__id__", field.getName(), -1, null,Integer.class, NoopConverter.class);
            continue;
        }

        Column annotation = field.getAnnotation(Column.class);
        if (! Objects.isNull(annotation)) {
            Class<?> converter = annotation.convertorClass();
            list.add(new ColumnInfo(annotation.name().trim(),
                    field.getName(),
                    annotation.index(),
                    annotation.dataFormat(),
                    field.getType(),
                    converter));
        }
    }

    if (list.isEmpty()) {
        throw new ZeroCellException(String.format("Class %s does not have @Column annotations", clazz.getName()));
    }
    list.trimToSize();
    return new ColumnMapping(rowNumberColumn, list);
}
 
Example 12
Project: android-schedules   File: JSONUtil.java   View Source Code Vote up 5 votes
/**
 * Convert an ArrayList of classes to a JSON array.
 *
 * @param classes ArrayList
 * @return JSONArray
 */
public static JSONArray classListToJsonArray(ArrayList<Class> classes) {
    if (classes == null || classes.isEmpty()) return new JSONArray();
    JSONArray json = new JSONArray();

    try {
        for (Class cls : classes) {
            JSONObject obj = new JSONObject();
            JSONArray tutors = new JSONArray();

            for (String tutor : cls.getTutors())
                tutors.put(tutor);

            obj.put("id", cls.getId());
            obj.put("lokaal", cls.getLocation());
            obj.put("starttijd", cls.getTimeStart().getTime());
            obj.put("eindtijd", cls.getTimeEnd().getTime());
            obj.put("commentaar", cls.getComments());
            obj.put("groepcode", cls.getGroups());
            obj.put("vakcode", cls.getClassName());
            obj.put("docentnamen", tutors);

            json.put(obj);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}
 
Example 13
Project: LQRWeChat   File: PlatformPageAdapter.java   View Source Code Vote up 5 votes
public PlatformPageAdapter(PlatformPage page, ArrayList<Object> cells) {
	this.page = page;
	if (cells != null && !cells.isEmpty()) {
		calculateSize(page.getContext(), cells);
		collectCells(cells);
	}
}
 
Example 14
Project: quake-alert-android-app   File: QuakeActivity.java   View Source Code Vote up 5 votes
@Override
public void onLoadFinished(Loader<ArrayList<Quake>> loader, ArrayList<Quake> earthquakes) {
    emptyView.setText(R.string.emptyText);
    emptyDesc.setText(R.string.emptyview_desc);
    mySwipeRefreshLayout.setRefreshing(false);
    emptyImageView.setImageResource(R.drawable.happy_earth);
    if (earthquakes != null && !earthquakes.isEmpty()) {
        updateUi(earthquakes);
        emptyImageView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
    }
    progressBar.setVisibility(View.GONE);
}
 
Example 15
Project: Bewitchment   File: Ritual.java   View Source Code Vote up 5 votes
public boolean isValidInput(List<ItemStack> ground, boolean circles) {
	ArrayList<ItemStack> checklist = new ArrayList<ItemStack>(ground.size());
	for (ItemStack item : ground)
		for (int j = 0; j < item.getCount(); j++) {
			ItemStack copy = item.copy();
			copy.setCount(1);
			checklist.add(copy);
		}

	if (checklist.size() != input.size()) {
		return false;
	}
	ArrayList<Ingredient> removalList = new ArrayList<Ingredient>(input);

	for (ItemStack stack_on_ground : checklist) {
		Ingredient found = null;
		for (Ingredient ingredient : removalList) {
			if (ingredient.apply(stack_on_ground)) {
				found = ingredient;
				break;
			}
		}
		if (found == null) {
			return false; //The stack on the ground doesn't belong to the rite
		}
		removalList.remove(found);
	}
	if (!removalList.isEmpty()) {
		return false;
	}
	return circles;
}
 
Example 16
Project: DijkstraAlgorithm-Java   File: DijkstraGraph.java   View Source Code Vote up 5 votes
/**
 * Gets the path from the target to the closest source
 * @param targetpoint is the Point you want the path to go from
 * @return List<Point> with the path to the closest source
 */
public List<DijkstraPoint> getPathFrom(DijkstraPoint targetpoint) {
	ArrayList<DijkstraPoint> shortestPath = new ArrayList<DijkstraPoint>();
	if(targetpoint != null) {
		DijkstraPoint currentPoint = targetpoint;
		shortestPath.add(currentPoint);
		while(!sourcePoints.contains(currentPoint)) {
			if(listOfPoints.get(currentPoint).pointWithLowestCost != null) {
				currentPoint = listOfPoints.get(currentPoint).pointWithLowestCost;
				shortestPath.add(currentPoint);
			} else {
				ArrayList<DijkstraPoint> connectedPoints = new ArrayList<DijkstraPoint>();
				for(DijkstraPoint[] connection : listOfConnections) {
					DijkstraPoint otherPoint = getOtherPoint(currentPoint, connection);
					if(otherPoint != null && !shortestPath.contains(otherPoint)) {
						connectedPoints.add(otherPoint);
					}
				}
				if(connectedPoints.isEmpty()) {
					break;
				}
				DijkstraPoint newPoint = connectedPoints.get(0);
				connectedPoints.remove(0);
				for(DijkstraPoint point : connectedPoints) {
					if(listOfPoints.get(point).aggregateCost < listOfPoints.get(newPoint).aggregateCost) {
						newPoint = point;
					}
				}
				currentPoint = newPoint;
				shortestPath.add(currentPoint);
			}
		}
	}
	return shortestPath;
}
 
Example 17
Project: ascii_generate   File: GetEmoticons.java   View Source Code Vote up 5 votes
private void writeFile(String title, ArrayList<String> list) throws IOException, ParserConfigurationException, TransformerException {
    System.out.println("GetEmoticons.writeFile");
    System.out.println("title = " + title);
    System.out.println("list = " + list);
    if (title == null || list == null || list.isEmpty()) return;
    String fileName = title.replaceAll("\\W", "") + ".xml";
    File file = new File("C:\\github\\AsciiGenerator\\app\\src\\main\\assets\\emoticons\\" + fileName);
    if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    org.w3c.dom.Document document = documentBuilder.newDocument();
    org.w3c.dom.Element root = document.createElement("root");
    document.appendChild(root);

    org.w3c.dom.Element name = document.createElement("name");
    name.appendChild(document.createTextNode(title));
    root.appendChild(name);

    org.w3c.dom.Element data = document.createElement("data");

    for (String s : list) {
        org.w3c.dom.Element item = document.createElement("item");
        item.appendChild(document.createTextNode(s));
        data.appendChild(item);
    }
    root.appendChild(data);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult streamResult = new StreamResult(file);
    transformer.transform(domSource, streamResult);
}
 
Example 18
Project: Exoplayer2Radio   File: WebvttDecoder.java   View Source Code Vote up 5 votes
@Override
protected WebvttSubtitle decode(byte[] bytes, int length, boolean reset)
    throws SubtitleDecoderException {
  parsableWebvttData.reset(bytes, length);
  // Initialization for consistent starting state.
  webvttCueBuilder.reset();
  definedStyles.clear();

  // Validate the first line of the header, and skip the remainder.
  WebvttParserUtil.validateWebvttHeaderLine(parsableWebvttData);
  while (!TextUtils.isEmpty(parsableWebvttData.readLine())) {}

  int event;
  ArrayList<WebvttCue> subtitles = new ArrayList<>();
  while ((event = getNextEvent(parsableWebvttData)) != EVENT_END_OF_FILE) {
    if (event == EVENT_COMMENT) {
      skipComment(parsableWebvttData);
    } else if (event == EVENT_STYLE_BLOCK) {
      if (!subtitles.isEmpty()) {
        throw new SubtitleDecoderException("A style block was found after the first cue.");
      }
      parsableWebvttData.readLine(); // Consume the "STYLE" header.
      WebvttCssStyle styleBlock = cssParser.parseBlock(parsableWebvttData);
      if (styleBlock != null) {
        definedStyles.add(styleBlock);
      }
    } else if (event == EVENT_CUE) {
      if (cueParser.parseCue(parsableWebvttData, webvttCueBuilder, definedStyles)) {
        subtitles.add(webvttCueBuilder.build());
        webvttCueBuilder.reset();
      }
    }
  }
  return new WebvttSubtitle(subtitles);
}
 
Example 19
Project: PigSPARQL   File: PigBGPBase.java   View Source Code Vote up 4 votes
/**
 * Generate JOIN statements for Triple Patterns.
 * 
 * @return
 */
protected String joinTriplePatterns() {
	List<Triple> triples = opBGP.getPattern().getList();
	joinBlock = "";

	Triple triple = triples.get(0);
	ArrayList<String> tripleVars = getVarsOfTriple(triple);
	// Schema of the first Triple is completely added to the resultSchema -> no duplicates possible
	addToResultSchema(tripleVars);

	int nextTriple = 1;
	ArrayList<String> joinVars;

	/*
	 * Iterate over all Triples in the BGP:
	 * 1. If a Triple has no shared variables with the current resultSchema we have to do a CROSS
	 * 2. If a Triple ha shared variables with the current resultSchema we can do a JOIN
	 * Successive CROSS statements can be reduced to one big CROSS
	 * Successive JOIN statements on the same variables can be reduced to one big JOIN
	 */
	while (nextTriple < triples.size()) {
		triple = triples.get(nextTriple);
		tripleVars = getVarsOfTriple(triple);
		joinVars = getSharedVars(resultSchema, tripleVars);
		int endPos;
		if (joinVars.isEmpty()) {
			/*
			 * Triple has no shared variables with the current resultSchema -> CROSS
			 * nextCross will generate one CROSS of all successive Triples with no shared variables
			 * nextCross returns the index of the last Triple in the generated CROSS
			 */
			endPos = nextCross(nextTriple);
		}
		else {
			/*
			 * Triple has shared variables with the current resultSchema -> JOIN
			 * nextJoin will generate one JOIN of all successive Triples with the same Join variables
			 * nextJoin returns the index of the last Triple in the generated JOIN
			 */
			endPos = nextJoin(nextTriple, joinVars);
		}
		// proceed with next Triple
		nextTriple = endPos + 1;
	}

	return joinBlock;
}
 
Example 20
Project: simple-share-android   File: DirectoryFragment.java   View Source Code Vote up 4 votes
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
	final SparseBooleanArray checked = mCurrentView.getCheckedItemPositions();
	final ArrayList<DocumentInfo> docs = new ArrayList<>();
	final int size = checked.size();
	for (int i = 0; i < size; i++) {
		if (checked.valueAt(i)) {
			final Cursor cursor = mAdapter.getItem(checked.keyAt(i));
                  if(null != cursor) {
                      final DocumentInfo doc = DocumentInfo.fromDirectoryCursor(cursor);
                      docs.add(doc);
                  }
		}
	}
          if(docs.isEmpty()){
              return false;
          }
	final int id = item.getItemId();
	switch (id) {
	case R.id.menu_open:
		BaseActivity.get(DirectoryFragment.this).onDocumentsPicked(docs);
		mode.finish();
		return true;

	case R.id.menu_share:
		onShareDocuments(docs);
		mode.finish();
		return true;

	case R.id.menu_copy:
		moveDocument(docs, false);
		mode.finish();
		return true;

	case R.id.menu_cut:
		moveDocument(docs, true);
		mode.finish();
		return true;

	case R.id.menu_delete:
		deleteDocument(docs, id);
		mode.finish();
		return true;

	case R.id.menu_stop:
		stopDocument(docs, id);
		mode.finish();
		return true;
	case R.id.menu_save:
          case R.id.menu_compress:
		new OperationTask(docs, id).execute();
		mode.finish();
		return true;

	case R.id.menu_select_all:
		int count = mAdapter.getCount();
		for (int i = 0; i < count; i++) {
			mCurrentView.setItemChecked(i, selectAll);
		}
		selectAll = !selectAll;
		Bundle params = new Bundle();
		params.putInt(FILE_COUNT, count);
		AnalyticsManager.logEvent("select", params);
		return true;

	case R.id.menu_info:
		infoDocument(docs.get(0));
		mode.finish();
		return true;

	case R.id.menu_rename:
		renameDocument(docs.get(0));
		mode.finish();
		return true;

	default:
		return false;
	}
}