masmic
masmic

Reputation: 3564

Delete object from array

I've got this constructor in the class Music:

protected String Title;
protected String Autor;
protected String Type;
protected int Code;

public Music (String title, String autor, String type, int code){
    this.setTitle(title);
    this.setAutor(autor);
    this.setType(type);
    this.setCode(code);
}

@Override
public String toString(){
    return this.Title + " " + this.Autor + " " + this.Type + " " + this.Code;
}

Then, in other class called ManageMusic I create some methods to then use them on the main class. I also define a String array refered to the Music class which I will use in the main class:

private final Music[] musicList;
private int counter;

public ManageMusic(int maxSize) {
    musicList= new Music[maxSize];
    counter= 0;

public void add(Music m){
    musicList[counter] = m;
    counter++;
}

Here, I have to create a delete method which would delete a especific object from the musicList and return this list without that object.

This is the way I add music elements to the musicList on the main class:

static ManageMusic musiclist = new ManageMusic(20);
musicList.add(new Music(title, autor, format, code));

My approach for the delete method in the ManageMusic class is to copy this list into a new String[] and then copy it back to the list. But as I'm using an objet from Music instead of from String, I cannot make the copy back because it does not cast the String to the musicList:

public void delete(int code){
        String[] newString = new String[musicList.length];
        int index_1 = 0;
        for (int i=0; i<musicList.length; i++){
            if(i != code){
                newString[index_1] = musicList[i].toString();
                index_1++;
            }
        }
        int index_2 = 0;
        for (int i=0; i<newString.length; i++){  //THIS IS WHERE IT SAYS: Cannot convert
                                                 // from String to Music
            musicList[index_2] = newString[i];
            index_2++;
        }
    }

I have to do something not far from this, because then I've got a method that list elements from the musicList, so I cannot set a return statement for the method.

Upvotes: 1

Views: 177

Answers (4)

Sebastian H&#246;ffner
Sebastian H&#246;ffner

Reputation: 1944

Why you can do it without an ArrayList

As some people suggested in the comments, you should probably use ArrayLists or similar stuff from the java.util.collection package.

However I assume you want to learn how such things work, so I will not provide you with code (First because I'm too lazy, second to encourage you to learn it yourself) but with some explanation.

edit: First: Your problem is that you copy strings, not references. Instead of trying to use the toString method, try to handle it with the "objects" (i.e. their references) themselves.

Error checking

As you might have noticed your add will cause an IndexOutOfBoundsException if you try to add another entry after your list reached your max_size. You should check for that. You should also check lots of things in the following explanations, I'll provide a few suggestions.

Simple deletion with your exact example

Just use Music[] instead of String[] and copy the reference of the temp Music[] to your musicList.

Better way to handle it: dynamic array structure

So what I suggest is to make use of a dynamic array structure. You will have to copy arrays around a lot, which can be a bit difficult. But basically it's what an ArrayList does.

Constructor

But how to implement that dynamic structure? Let's first start with the initialization, i.e. your constructor. You will not need a parameter for a maximum size (unless you want to restrict your music collection for some reason). Just create an array with size 0. (Of course you can also implement copy constructors and other things, but for the start keep it simple.)

add()

To add more music, you simply create a new array with the size of your current collection + 1, copy all references (this is probably the answer you were looking for. You take the strings, but just take the objects themselves) from the current array to the new array, add the new Music and change the reference of your member variable to your newly created, bigger array (i.e. assigning musicList = tempArray; or something similar). (Error checking: is the object null?)

delete()

For deletion you can do just the same. Create a new temporary array (this time with a reduced size), copy all values over but leave out the one you want to delete. To determine which shall be deleted you can either check for indices or even check the objects for equality. (Error checking: size of temp array should never be smaller than 1, so check if your array is empty - consider to use a method like isEmpty() for that.)

Why should I do this?

Once you got those concepts you will be able to manage your array in whatever way you like. Search through it, delete all elements, copy your music collection to your friend's, etc. etc.

And beyond that?

And after you learned this, go ahead and try the ArrayList - you will figure out it works very much like what you have just written. And now you can be proud that you not only can use ArrayLists, but also know how and why they behave like they do.

Upvotes: 1

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

do like this

public void delete(int code){       
    List<Music> list = new ArrayList<Music>(); //creating new empty list
    for (Music m:musicList){
        if(m.code != code){ // removing condition
            list.add(m); // adding music to new list
        }
    }
    musicList = list.toArray(new Music[list.size()]); // assigning back list to musicList 
}

Upvotes: 1

NickJ
NickJ

Reputation: 9559

ArrayList example:

List<Music> musicList = new ArrayList<Music>();

adding to end of list list:

musicList.add(new Music(...));

adding to specified position in list (later ones all move up one place)

musicList.add(index, new Music(..));

remove from list:

musicList.remove(index);

or

musicList.remove(someMusic);

Size of list:

int size = musicList.size();

Get first music:

Music first = musicList.get(0);

Get last music:

Music last = musicList.get(musicList.size()-1);

Loop:

for (Music : musicList) {
  //do stuff
}

Upvotes: 1

Vimal Bera
Vimal Bera

Reputation: 10497

Its better to use ArrayList than writing own logic to delete object from existing array. Here is how you can use ArrayList :

{
    ArrayList<Music> list = new ArrayList<Music>();
    Music m1 = new Music(title, autor, format, code);
    list.add(m1);
    // similarly you can check whether object is present in ArrayList or not using
    if(list.contains(m1)){ // This check whether object is present in ArrayList or not
          //Do whatever you want
    }
}

Upvotes: 1

Related Questions