[Beginner][Tut] Simple ArrayLists

Discussion in 'Resources' started by Bailey Payne, May 15, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Bailey Payne

    NOTE:
    If you are experienced this tutorial is not for you, so do not read!

    I have seen way to many people not knowing how to do simple ArrayLists, which is shocking since its basic java, so this is a fast short and easy tutorial on how to make sure you do them right.

    Step 1:

    Firstly we need to create our ArrayList!

    Code:java
    1. //Creating the ArrayList under the name al
    2. ArrayList al = new ArrayList();


    Step 2:

    Now we made it we need to add Players to it so we can use the list of players. For the use of this tutorial i am using a PlayerJoinEvent but you can add them however you want, its the actual adding part which matters!

    Code:java
    1. //Creating the ArrayList under the name al
    2. ArrayList al = new ArrayList();
    3.  
    4. //Player Join Event, adding people to the ArrayList
    5. @EventHandler
    6. public void onPlayerJoinEvent(PlayerJoinEvent e){
    7. //Getting who joined
    8. Player p = e.getPlayer();
    9.  
    10. //adding player to the ArrayList
    11. if(!al.contains(p){
    12. al.add(p);
    13. }
    14. }


    Step 3:

    Now your Player is added you can do what you want with it, you just have to use the ArrayList, which in this case is named "al". I wont do this step, since there is so much you could do!

    Step 4:

    Removing a player from the ArrayList, if you need to do this. I have used the PlayerQuitEvent for this, but you can remove them anyway you want.

    Code:java
    1. //Creating the ArrayList under the name al
    2. ArrayList al = new ArrayList();
    3.  
    4. //Player Join Event, adding people to the ArrayList
    5. @EventHandler
    6. public void onPlayerJoinEvent(PlayerJoinEvent e){
    7. //Getting who joined
    8. Player p = e.getPlayer();
    9.  
    10. //adding player to the ArrayList
    11. al.add(p);
    12. }
    13. //Player Leave Event, removing people from ArrayList
    14. @EventHandler
    15. public void onPlayerLeaveEvent(PlayerQuitEvent e){
    16. //Getting who left
    17. Player p = e.getPlayer();
    18.  
    19. //removing player from ArrayList
    20. if(al.contains(p)){
    21. al.remove(p);
    22. }
    23. }


    And Thats it! This Tutorial is VERY basic, and is meant for the very new members, which i hope it helped!
     
    AlexHH251997 likes this.
  2. Offline

    DxDy

    Your tutorial could benefit from proper intendation ;)

    Also:
    Code:java
    1. if(al.contains(p)){
    2. al.remove(p);
    3. }

    is quite redundant ;) You could just as well do al.remove without checking if the element is actually in the list.
     
  3. Offline

    Bailey Payne

    I could've, but doing the check may be better for different purposes, as people may need to do it.
     
  4. Offline

    macguy8

    Bailey Payne
    You should certainly mention that storing the Player object is a bad practice, and possibly touch on generics.
     
  5. Offline

    Zupsub

    Instead of using ArrayList al = new ArrayList();
    use
    List al = new ArrayList();

    Then you can change it to a LinkedList for example.

    Don't name your variables useless:
    Instead of "al" use "playerList", or even better in this case "playerOnlineList"

    As macguy8 mentioned, use generics!
    So all-in-all:
    List<Player> onlinePlayersList = new ArrayList<>();
    Would be much niecer.
     
  6. Offline

    L33m4n123

    Why is it bad practice? If you can't handle them. thats bad practice. You just need to know Java and know when to store/remove player object
     
  7. Offline

    macguy8

    L33m4n123
    I know it's not a bad practice, but consider the scope of this tutorial. Any developer worth his salt would know to GC the list properly, however if you have to look up how to use an ArrayList I doubt you'd know you need to closely monitor the list to prevent leaks.
     
  8. Offline

    Adriani6

    Why make tutorial on basic java ? Java Docs don't exist ?

    I'm sorry, but c'mon, even if you don't know Java, you should know that those languages have their own documentation...

    I am not hating on this post.
     
  9. Offline

    garbagemule

    I'm not sure if it is a type of defensive move on your part to pardon your own lack of syntactical expertise with Java, but I think that if anything, beginner tutorials should be peer reviewed by seasoned developers. I applaud the good intentions of wanting to help out beginners, but if you are a beginner yourself, you should welcome more experienced developers, not try to push them away. As with most written works, revisions are sometimes necessary to make them truly great :)

    And on that note, I would like to reiterate (and perhaps fully manifest) a few points made by other commenters:

    Program to an interface, not an implementation

    A clear favorite of mine when it comes to object-oriented programming principles. Unless you need specific ArrayList-only methods, you should be declaring variables of type List (or Collection), rather than variables of type ArrayList. The reason for this is abstraction. Consider this method signature:
    Code:
    public ArrayList<String> getNames()
    Looks innocent, right? It's not. Let's say that this method returns an ArrayList of names of players that are currently online. Then for some reason, you decide that you want to return a LinkedList instead (unlikely, as LinkedList is less efficient for all list operations in practice), so now you have to change the method signature:
    Code:
    public LinkedList<String> getNames()
    In the meantime, some other developer has hooked into your plugin and is now using this method in his own plugin. When you change the method signature of a public facing method, you risk breaking anything that depends on that method (this is what happened when health changed from ints to doubles in Minecraft, and the only reason this didn't break Bukkit plugins was due to a clever hack by the Bukkit team to ensure backwards compatibility), so there are reasons beyond "it's annoying to have to change all my methods" when you decide to use a different implementation for something. Had you instead started out with this signature:
    Code:
    public List<String> getNames()
    You would have absolutely no problem changing to a different implementation of the List interface, because you would still be returning a compatible object. This could also be problematic, though, because is it actually necessary to return a List, or would a Collection suffice? If add, remove and contains are the only required operations, then this signature would be even better, because it would allow you to change the implementation to e.g. a HashSet (or a TreeSet, if you wanted to return an ordered collection):
    Code:
    public Collection<String> getNames()
    So, program to an interface, not an implementation, because abstraction is one of the fundamental principles of object-oriented programming, and ignoring them creates tightly coupled, inflexible code that is more prone to breaking stuff when things are shifted around.

    Generics

    This is an understatement:
    The Collections framework makes very, very heavy use of generics, and for good reasons. Generics is a somewhat controversial feature that aims to help make code more type safe. Consider this statement:
    Code:
    ArrayList list1 = new ArrayList();
    There is absolutely no information about what types of objects this list will contain. Not knowing what a collection contains makes it difficult to reason about, and extremely prone to ClassCastExceptions, because you will be forced to cast the elements to what you think the collection contains. It is basically the same as creating a List<Object>, which is extremely vague.
    Code:
    List<String> list2 = new ArrayList<String>();
    This statement is not only better because it uses the interface type for the variable, but also because it clearly signals what type of objects it can contain - strings. With list1, you will be able to add whatever you want to it. Sounds like a good thing? It's not. If you are creating a list of strings, make it explicit so other people (and yourself) can easily see what they are dealing with. Consider list iteration with an enhanced for-loop:
    Code:
    for (Object o : list1) {
        String s = (String) o;
        if (s.equals("Alice")) {
            System.out.println("I found her!");
        }
    }
    for (String s : list2) {
        if (s.equals("Alice")) {
            System.out.println("I found her!");
        }
    }
    Notice how it is necessary to explicitly cast the loop variable to a String when iterating list1, but list2 is guaranteed to be a list of strings at compile-time, so the compiler will happily allow you to iterate it, assigning each element to the loop variable of type String.

    TL;DR

    The statement "ArrayList list = new ArrayList()" has two problems:
    1. Don't program to an implementation. Use List for the variable type instead of ArrayList.
    2. No generics means the type of the list elements is not specified. Use e.g. "new ArrayList<String>()" if creating a list of strings.

    If you thought Javadocs were easier to learn from than actual learning material aimed at newbies when you first started learning Java, you either had experience with other programming languages and their documentation, or you are just plain weird. Having taught introductory programming for a few years now, I haven't heard a student say that Javadocs are easier to learn from than designated learning material. In fact, I don't think I've ever heard anyone say that and mean it. Sure, you can learn a programming language by reading the language specification. You can also just crawl on your knees anywhere you want to go, but I'm sure you prefer a different mode of transportation, e.g. walking, riding a bike, driving a car, etc.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 8, 2016
    DxDy likes this.
  10. Offline

    Adriani6

    You are sure right, as I said in my post this is not a 'hate' post. What I meant is... why would you post a basic java resource in bukkit forums, where I believe (obviously, that's my opinion, as we are all entitled to have) we should be posting bukkit api resources and not teaching people java as I believe people who have experience/knowledge with it are most likely to be the ones browsing in that section. Saying that, if you don't know anything about programming, why bother with bukkit api which requires knowledge of java ?
    Again, I am not hating, starting and forum wars or anything, just clarifying things and posting my opinions about it.
     
  11. Offline

    garbagemule

    Programming is just a craft like any other craft. People just don't learn it without a purpose. If you have ever thought about learning a new programming language because it "seems cool" or because it makes things you usually see as complicated a total breeze (I'm REALLY looking forward to being able to put lambda expressions to use in production Java code), you'll know just how difficult it is to stay motivated if you just keep writing useless Hello World applications. If you have a real goal, and if the learning material you find is relevant to your goal, it gets so much easier to stay motivated. There are plenty of reasons why the resources section needs really good beginner tutorials, but I do think that they ought to be bundled up into one high-quality package of sorts, such that most of the visible threads could be about Bukkit API stuff, like you mention.

    I don't think anyone is taking any offense from your posts, so you don't have to be explicit about not wanting to offend. Besides, justified skepticism is much more constructive than blind trust. Questioning the worth or relevance of a post like this, and doing it with good intentions of either learning something new (personal growth) or sharing your opinion (helping and influencing the community you are a part of), is completely justified :)
     
    bobacadodl and oaschi like this.
  12. Offline

    Adriani6

    I agree, makes more sense, in this case bukkit could be expanded (resources section) to Bukkit API resources and Java Resources I guess and it would make more people happy. I'm not going to go into more discussion as I don't want to spam this thread with comments which are useless to those learning ;)

    I also appriciate your understanding of my comments, I just stated that incase someone finds it harsh since a lot of my posts are seen this way when I express my opinions :)

    Either way, some good points presented :)
     
  13. Offline

    RawCode

    you shoud carefully read javadocs about native class you going to describe or explain.

    your tutorial is invalid, if you going to explain how arraylist works, explain it right and complete:

    Code:
    439     public boolean remove(Object o) {
    440         if (o == null) {
    441             for (int index = 0; index < size; index++)
    442                 if (elementData[index] == null) {
    443                     fastRemove(index);
    444                     return true;
    445                 }
    446         } else {
    447             for (int index = 0; index < size; index++)
    448                 if (o.equals(elementData[index])) {
    449                     fastRemove(index);
    450                     return true;
    451                 }
    452         }
    453         return false;
    454     }
    
    As you may see, removing specific element will remove all instance of that element from array if such object inside array.
    Removing null element will remove ALL nulls from array.

    There is no reason to check if object present before adding or removing it, since implementation of array list work in a bit different way.

    without such information tutorial is misleading and invalid.
     
  14. Offline

    DxDy

    That is not true. Not by documentation:
    and not by the code you posted, which clearly exits as soon as the first matching element in the list was found.
     
    garbagemule likes this.
Thread Status:
Not open for further replies.

Share This Page