zondag 17 april 2011

Linked Lists to store classes into - Example

The applet above uses Linked Lists to store classes into. I think I remember that being called instances of classes? I have no idea if when you remove a linkedlist item from the List if then the class is closed to.

I was looking through the java source code that I downloaded in the last few weeks. I discovered that I downloaded a Dijkstra path finding example and was studying how it uses open and closed lists. I was working on a path finding example and could not figure out how to do the open and closed lists. I see that Java has Linked Lists. .

Below are several lines of code the I think are needed for setting up the linked lists.

import java.util.LinkedList;

//Placed in the main class
LinkedList nodes, openlist, closedlist ;

//Placed in the init() part
nodes = new LinkedList() ;
closedlist = new LinkedList() ;
openlist = new LinkedList() ;

closedlist.add(best) ;
openlist.remove(best) ;

I have gotten it working. I can add classes to a linked list and remove them to. I also took a look at Lists that Java has but I could not get it working with classes.

I have no idea if this is the best way to create the sprites and particles ect.. in Java. I found a tutorial and found it uses regular arrays to store sprite classes in but arrays can not be resized. Linked Lists can have their contents removed and added to. I also found the Lists feature but do not understand it yet.

Below is the source code of the example applet.


import java.awt.*;
import java.applet.*;
import java.util.LinkedList;
import java.util.Random;

public class ListTest02 extends Applet {

 LinkedList enemies = new LinkedList();
 Random r1 = new Random();

 public void init()
  // Test adding items to linked list
  for(int i = 0 ; i <= 30 ; i++){
   enemies.add(new theEnemies(r1.nextInt(200),r1.nextInt(200)));
  // Test removing of item from linked list.

 public void paint(Graphics g)

  g.drawString("Welcome to Java!!", 50, 60 );

  theEnemies theenemies;
  for (int i = 0 ; i < enemies.size();i++) {
   theenemies = (theEnemies)enemies.get(i);


 class theEnemies
  private int x;
  private int y;
  private int w;
  private int h;
  public theEnemies(int x1,int y1)
  public int getx()
   return x;
  public int gety()
   return y;


Geen opmerkingen:

Een reactie posten