I am creating an android application, and I created a list of available files in the internal memory with this instruction:
final String[] files =fileList();
I need to remove a file from this list and I don't know how, can you help me?
To "remove" something you can just set it back to null, or you can do it the hard way with a loop that shifts everything behind it up a place.
public void remove( int index ) {
for(int i=index; i<sarr.length()-1; i++) {
sarr[i] = sarr[i+1]
}
sarr[sarr.length()-1] = null;
System.out.println("Removed!");
}
When using primitive arrays like this, there is no removal method. If you built a more complex datatype you could have the "remove" method available to you.
Use a List<String> instead. That way you can remove the file that you want using the remove() method.
index = 0//location of item to be removed, with the first item in the list at 0
List<String> files = Arrays.asList(getFiles());
files.remove(index)
in this example, index is the location of the item that you want to remove. Alternatively, you could do this instead
item = "fileLocation";
List<String> files = Arrays.asList(getFiles());
files.remove(item)
Related
I have a JTable with three columns, each of which is filled with an array made from an ArrayList. I am trying to make a search system, where the user will search for a value in the first column, and the rows of the JTable will filter out, so that only the rows that contain the specified String from the search box show up on the table after a button is pressed. On another table, this worked by filtering the ArrayList used using this loop:
String s = searchBar.getText();
ArrayList<String> fn = new ArrayList<>();
fn.addAll(names); //names is the arraylist that contains all the values that will be filtered
for(Iterator<String> it = fn.iterator(); it.hasNext(); ) {
if (!it.next().contains(s)) {
it.remove();
}
This code works to filter out the array, but what I am trying to do is filter 3 ArrayLists based on only if one of the ArrayLists does not contain the s String.
I tried doing this:
String s = searchBar.getText();
ArrayList<String> fn = new ArrayList<>();
ArrayList<String> fp = new ArrayList<>();
fn.addAll(names); //names is the arraylist that contains all the values that will be filtered
fp.addAll(numbers)//one of the other arraylists that I want to filter
for(Iterator<String> it = fn.iterator(), itp = fp.iterator(); it.hasNext() && itp.hasNext(); ) {
if (!it.next().contains(s)) {
itp.remove();
it.remove();
}
When I run this code I get a Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException on the line where I write "itp.remove();".
Is there a way I can remove from both the arrays based on only one of them?
I'm happy that you fix your exception. Anyway, when I said about back iteration I meant something like that
Firstly, Some of check like
if(fn.size()==fp.size()){
// and after that go to delete.
for (int i=fn.size(); i>0;i--) {
if (fn.contains(s)) {
fn.remove(i);
fp.remove(i);
} }}
Anyway, your and my method isn't good for multithreading, because ArrayList doesnt't concurrent object also it's remove method
So I managed to fix it by using the remove method from the ArrayList instead of the remove method from the Iterator. I know this isn't the recommended way of doing it, but it seems to not have brought any negatives with it, so I will keep it for now.
The code I used is:
int i = 0;
for (Iterator<String> it = fn.iterator(); it.hasNext(); i++) {
if (!it.next().contains(s)) {
it.remove(); //Iterator's remove
fp.remove(i);// ArrayList's remove which avoids the error
}
}
Thank you to all who helped
public ArrayList<String> getWords()
{
int size1 = lines.size();
int size2 = 0;
int counter3 = 0;
ArrayList<Integer> checkthewords;
for (int x = 0; x < size1; x++)
{
size2 = lines.get(x).substring(x).length();
for (int y = 0; y < size2; y++)
{
if (Character.isLetter(charAt(((lines.get(x)).indexOf(x, z + x)))))
{
words.set(z, lines.get(x).substring(x,z + 1));
}
else
{
checkthewords.set(counter3, words);
counter3++;
}
if (checkthewords.get(x).equals(checkthewords.get(counter3)))
{
}
}
}
return words;
}
The method above is a called getWords(). I am trying to get a word from a file and store it in the arrayList checkthewords. I want to make sure that a word is not going to be stored in the arrayList checkthewords more than once.
I have the if statement:
if (Character.isLetter(charAt(((lines.get(x)).indexOf(x, z + x)))))
But, don't know where to go from there.
I'm pretty sure your code won't run at the moment. You are doing some strange things in there and I don't really understand it.
Try to approach this one step at a time.
The first step is to get the word from the file. Make sure you can parse the line and extract the word you want.
Then you need to check if the word exists in your checkthewords list. If it doesn't exist, add it. You can use the contains method provided by List to see if the list contains something.
if(!checkthewords.contains(word)) {
// it's not in the list yet, add it
checkthewords.add(word);
}
Also when you create your checkthewords list, you don't initialise it (so it's null):
ArrayList<String> checkthewords;
should be:
ArrayList<String> checkthewords = new ArrayList<String>();
And you shouldn't use checkthewords.set() like that. set is used to replace an existing element, not to add a new element. You could easily be setting an element that doesn't exist yet and throw an ArrayIndexOutOfBoundsException. Use checkthewords.add(word) to add something to your list.
See the ArrayList documentation.
set(int index, E element)
Replaces the element at the specified position in this list with the specified element.
It seems like you're overthinking this. Keep it simple. :)
You should use Set in Java to store elements when duplicates are not allowed.
A collection that contains no duplicate elements.
If you want to retain insertion order as well then use LinkedHashSet which is Hash table and linked list implementation of the Set interface, with predictable iteration order.
Kindly refer to below tutorials to understand application of Set in java.
Tutorial 1
Tutorial 2
Tutorial 3
See Also-:
HashSet vs TreeSet vs LinkedHashSet
HashSet vs LinkedHashSet
Can someone show me how to remove an object from an array. But here's the catch (well for me), the array is something like this
member[0] = new Member("John Cena" , "p000001");
I want to be able to search a name, then when that is detected, to be able to remove. is it possible?
public static void remove(){
System.out.println("Name: ");
String removeName = input.next();
System.out.println("ID: ");
String removeID = input.next();
for(int i = 0; i < member.length; i++){
//not sure if this is the right direction
}
}
EDIT: Cannot use ArrayList or list because of requirements in an Assignment. Would have used it since it is easier but can't.
You can either use an ArrayList (or better yet, ArrayList<Member>), which you can populate with members, and then use the indexOf method to search through.
Alternatively, if you have to or would rather use arrays, create a loop like you have that iterates through each index of your members array. The only tricky part is removal requires that you remove it from the array, and then shift each index in front of it down so that the blank space is remove.
In other words, you need to delete index i and use a loop so that you move the member at i + 1 down to i, member i + 2 moves down to i + 1, and so on until you reach the end of the array.
With all that being said, I'd encourage use of the ArrayList. It does all of the operations I just described for you and makes matters a lot easier.
Arrays are fixed-size. This means that the best you can do for an object array is set the value to null. If you want to remove it completely, you'll want to use ArrayList instead. In that case,
ArrayList<Member> members = new ArrayList<Member>();
for (int i = members.length-1; i>=0; i--) {
if (members.get(i).getName().equals(toRemove)) {
members.remove(i);
}
}
Sorry for my previous wrong answer. This should be the correct way of removing your Members
List<Member> l = new ArrayList<>(Arrays.asList(member));
for (Iterator<Member> iter = l.listIterator(); iter.hasNext(); ) {
Member a = iter.next();
if ( (a.getId() == removeID) || (removeName.equals(a.getName)) ) {
iter.remove();
}
}
Member[] newMembers = l.toArray(new Member[l.size()]);
PS: Please get removeID like this;
int removeID = input.nextInt();
It's a bit wonky that you have to use an array, because:
You can't truly guarantee that there isn't going to be more than one person with the same name, since the array doesn't guarantee unique entries.
Arrays don't dynamically resize, leaving you to have to do that yourself.
It can still be done though. Here's an example using Java 8's Stream API.
Let's assume you're looking for a Member with the same name and ID. Then, you're going to want to filter out any elements that are not that entry, collect them to a List, and then turn that List into an array.
So the result would be:
member = Arrays.stream(member)
.filter(m -> removeName.equals(m.getName())
&& removeID.equals(m.getID()))
.collect(Collectors.toList())
.toArray(new Member[0]);
Is it possible to add items dynamically to a RDFList in Jena?
Something like:
RDFList list = model.createList(new RDFNode[] {});
//string with names of rdf classes
String[] parts = list.split("-");
for(int i = 0; i<parts.length; i++){
OntClass oclass = model.getOntClass("http://example.org/"+parts[i]);
list.add(oclass);
}
I'm getting
com.hp.hpl.jena.rdf.model.EmptyListUpdateException: Attempt to add() to the empty list (rdf:nil)
Thanks in advance
Without seeing all of your code and what some of the values are, we can't be sure what's happening, but I think the problem here is that you can't use RDFList#add with an empty list, and I think that's what you're creating at the start. Since you're creating a list with no elements, you should be getting rdf:nil back, which is the empty list. Note that the documentation for RDFList#add says:
If this list is the empty (nil) list, we cannot perform a side-effecting update without changing the URI of this node (from rdf:nil) to a blank-node for the new list cell) without violating a Jena invariant. Therefore, this update operation will throw an exception if an attempt is made to add to the nil list. Safe ways to add to an empty list include with(RDFNode) and cons(RDFNode).
You didn't mention whether you're getting that exception or not.
In your case, I think the easiest thing to do would be to create the array of OntClasses, and then just create the list from them. That is, you could do something like (untested):
String[] parts = list.split("-");
RDFNode[] elements = new RDFNode[parts.length];
for(int i = 0; i<parts.length; i++){
elements[i] = model.getOntClass("http://example.org/"+parts[i]);
}
RDFList list = model.createList(elements);
Alternatively, if you want to use with, as mentioned in the documentation, you'd do something like (again, untested):
RDFList list = model.createList(new RDFNode[] {});
//string with names of rdf classes
String[] parts = list.split("-");
for(int i = 0; i<parts.length; i++){
OntClass oclass = model.getOntClass("http://example.org/"+parts[i]);
list = list.with(oclass);
}
For a bit more about this, you might find this answer of mine and the comments on it relevant. You're not the first one to have had a bit of a struggle with RDFLists.
I am looking for a java data structure similar to an ArrayList that when I do an add or a push with only a value argument an index will be returned for me automatically.
For example:
ArrayList<String> elements = new ArrayList<String>();
String element = "foo";
String elementTwo = "bar";
int index1 = elements.add(element); //note this does not exist, i.e. returns bool in api
int index2 = elements.add(elementTwo);
System.out.println(elements.get(index1)); //would give "foo"
I could see writing a wrapper class around ArrayList that manages a counter that is incremented on every add operation and invoking:
ArrayList.add(int index, E element)
Do you really need to write a wrapper around ArrayList for this? This seems like something simple enough to be provided out of the box somewhere?
Edit:
I need the index (key) to be fixed and unique for this usecase. A map was suggested and I agree with that. Does anyone know of a map implementation that gives you an automatically (uniquely) generated key on a value insert? I am just trying to decide if I need to implement my own wrapper for this.
The element will be added at the end of the list. So you can use elements.size()-1 to get the new elements index.
Note that this will not work reliable if multiple threads are modifying the list at the same time.
EDIT: Also note that it might not be a good idea to use an ArrayLists index as a unique ID because an elements index can change (for example when you remove an element or insert a new one using add(int, Object)). If this is a problem depends on what you want to do with the index: If you only need it for a short time after adding an element and can be sure that the list is not modified in the meantime, there is no problem. In the other case even a method returning the index when calling add(Object) would not help because the index does not get updated in anyway. To prevent this issue you can:
Make sure you never remove elements from the list and never add elements using add(int, Object).
Instead of removing elements you could also set them to null using the method set(int, null). This way no elements index will change.
Use some other data structure like for example a map with a custom ID like helloannalil suggests in his answer.
EDIT 2: I did not find a appropriate, ready to use implementation (but this does not mean there is none, of course). To suggest a good solution, more information on the intended use of the data structure is needed, but here are some ideas and notes:
If the maximum number of elements is not to large, an ArrayList could be used and the elements index represents the ID. As stated above, to remove an element it can be set to null so that no indices are changed. When inserting, positions with null values can be reused.
You can also use one of the two methods show in this answer: https://stackoverflow.com/a/8939049/1347968 (keywords AtomicLong or IdentityHashMap)
Do not depend on the "uniqueness" of Object.hashCode() or System.identityHashCode(Object) as it is not guaranteed (try it by running the example at the bottom of Suns/Oracles Bug #6321873).
Well what I do in that cases (I love ArrayLists) is to get the last index by asking the size of the list:
String thing = "theThing";
List<String> strList = new ArrayList<String>();
strList.add(thing);
int indexOfThing = strList.size() - 1;
I mean, is easier than implement your own List and just works.
if you really want this function, you can use map but not list
Based on your comments and edited question I think you can extend a HashMap for your use like this:
public class MyMap<V> extends HashMap<Integer, V> {
private static final long serialVersionUID = 1L;
public int add(V elem) {
int key = System.identityHashCode(elem);
super.put(key, elem);
return key;
}
}
Then inside your class declare MyMap like this:
private MyMap<String> map = new MyMap<String>();
And then add your elements to MyMap like this:
.....
.....
String element = "foo";
String elementTwo = "bar";
int index1 = map.add(element);
int index2 = map.add(elementTwo);
Now you have index1 and index2 as indices of you inserted strings that you can use or pass around for the lifetime of your application. You can insert or remove elements in MyMap as many times you want but your indices (index1 and index2) will give you back your inserted elements like this:
String elem1 = map.get(index1); // will return "foo"
String elem2 = map.get(index2); // will return "bar"
String thing = "theThing";
List<String> strList = new ArrayList<String>();
strList.add(thing);
int indexOfThing = strList.size() - 1;
If you remove an item, this will no longer work.