Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
yatagan
Aug 31, 2009

by Ozma
Because I'm such a nice guy, here's the base code fixed. There may be a neat linear algebra solution, but that's why we have fancy packages that do things like that like those I linked in the last post. You will need to make sure your base data is organized like the program is expecting.

Just do me a favor and don't come around here using variables based on a object named system that is not actually a System object ever again though.

code:
int n = system.arrayWidth;
int[][] initMatrix = new int[n][n];
int[][] progressMatrix = new int[n][n];
int[][] tempMatrix = new int[n][n];

for (int row = 0; row < n; row++) {
	for (int col = 0; col < n; col++) {
		int val = system.graphMatrix[row][col];
		initMatrix[row][col] = val;
		progressMatrix[row][col] = val;
		tempMatrix[row][col] = 0;
	}
}

for (int powerCount = 0; powerCount <= n + 1; powerCount++) {
	for (int row = 0; row < n; row++) {
		for (int col = 0; col < n; col++) {
			for (int iter = 0; iter < n; iter++) {
				tempMatrix[row][col] += progressMatrix[row][iter] * initMatrix[iter][col];
			}
		}
	}

	for (int row = 0; row < n; row++) {
		for (int col = 0; col < n; col++) {
			progressMatrix[row][col] = tempMatrix[row][col];
			tempMatrix[row][col] = 0;
			System.out.print(progressMatrix[row][col] + " ");
		}
		System.out.println();
	}
	System.out.println();
}

Adbot
ADBOT LOVES YOU

FreshShoez
Oct 15, 2009
Hey, thanks! The "-1" screwed up the part you were talking about, and the function I made that reset matrices to zero. Fixed those, and everything is working smoothly as far as I can tell. I appreciate the links to the extra math libraries, but unfortunately, we're not allowed to use any external libraries. I thought about 'peaking' at the code in some external libraries and using their strategy for dealing with matrices, but then decided that the teacher probably wanted the textbook definition for matrix multiplication instead of an optimized, sane-person algorithm. But the other part of what you said fixed it anyway, so thanks again!

yatagan
Aug 31, 2009

by Ozma
No problem. Out of curiosity, how does this tie into detecting deadlock?

Fly
Nov 3, 2002

moral compass

Kilson posted:

It doesn't stop or exit, it just continues running (after skipping whatever code it skips) as if nothing ever happened.
Do you have some logging that indicates it is still running? Can you post the code that supports your observation?

FreshShoez
Oct 15, 2009
It's a linear adjacency matrix that represents a process-resource graph. The matrix has 1s for where there are edges in the graph, and 0s for where there are not. If a process-resource graph has no loops, it isn't deadlocked. Taking an adjacency matrix to the (n+1) power will check if it has loops (if it's not all zeros by that point, there's a loop).
As for the 'system' variables, the professor wanted a 'system' variable container that held how many processes the system had, how many resources, and the adjacency matrix. In this case I decided to reference it as a generic "system", and in more specific parts of the code I referenced it as "sys1", "sys2", etc. Sorry for the confusion.

edit: and by loop, I mean cycle

Contra Duck
Nov 4, 2004

#1 DAD

Kilson posted:

It doesn't stop or exit, it just continues running (after skipping whatever code it skips) as if nothing ever happened.

Are you absolutely certain that the code being executed is the same version as the source code you're looking at? I realise it sounds silly but I know in the past I've wasted hours trying to figure out why my changes weren't working only to realise that I'd been deploying the wrong package and my changes hadn't been going in at all :v:

StickFigs
Sep 5, 2004

"It's time to choose."
Why won't my Fibonacci thing work?:

code:
import java.util.ArrayList;


public class DumbFibonacci extends ActivationRecord{
	
	//public static Integer resultHold;
	Integer resultHold = null;
	
		public DumbFibonacci(ArrayList<Integer> arr){
		currentLine = 1;
		arglist = arr;
		//Integer resultHold = null;
	}
	
	void methodBody(){
		
		switch(currentLine){
			case 1: {
				lineOne(arglist.get(0));  
				break;
			}
			case 2: {
				lineTwo(arglist.get(0));
				break;
			}
			case 3: {
				lineThree(arglist.get(0));
				break;
			}
			case 4: {
				lineFour(arglist.get(0));
				break;
			}
			case 5: {
				System.out.println("popping DumbFibonacci(" + arglist.get(0) + ") with result = " + result);
				endProcess();  // pop this call from the stack
				break;
			}
			default: {
				break;
			}
		}
	}
	
	void lineOne(int k){
		System.out.println("pushing DumbFibonacci(" + k + ")");
		
		if (k <= 1) {
			currentLine = 5; // base case - exit 
			result = 1;
		}
		else currentLine++; // or continue to next line
	}
	
	void lineTwo(int k) {
		ArrayList<Integer> arr = new ArrayList<Integer>(1);
		arr.add(k-2);
		callingStack.push(new DumbFibonacci(arr));
		currentLine++;  // on to next line
	}
	
	void lineThree(int k) {
		ArrayList<Integer> arr = new ArrayList<Integer>(1);
		resultHold = k;
		arr.add(resultHold-1);
		callingStack.push(new DumbFibonacci(arr));
		currentLine++;  // on to next line
	}
	
	void lineFour(int k) {
		result = k;
		currentLine++;  // on to next line
	}
	
}
Ignore the weird simulated process stack thing, what I'm trying to do is Fibonacci with recursion and it looks like it's working in the console but when it gets to the end (In the case I'm testing it in, the Fibonacci factor or whatever of 4) and at 4 it should be 5 but it's 4. How am I loving up?

yatagan
Aug 31, 2009

by Ozma

StickFigs posted:

Why won't my Fibonacci thing work?:

I don't know but it's painful to try to decipher. This is a recursive Fibonacci sequence:

code:
public int doFib(int x) {
  if (x <= 0) {
    return 0;
  } else if (x == 1) {
    return 1;
  } else {
    return doFib(x-1) + doFib(x-2);
  }
}

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

StickFigs posted:

Ignore the weird simulated process stack thing, what I'm trying to do is Fibonacci with recursion and it looks like it's working in the console but when it gets to the end (In the case I'm testing it in, the Fibonacci factor or whatever of 4) and at 4 it should be 5 but it's 4. How am I loving up?

It's impossible to say without knowing the return-value convention, but my guess is that both lineThree and lineFour are wrong. lineThree is saving the argument to this activation instead of the result from the first recursive call. lineFour is returning the argument to this activation instead of the sum of the results of the recursive calls.

This is a very silly simulation, by the way. It would be much better to force students to write a simple stack machine with a fixed instruction set and then write a recursive fibonacci in that machine's assembly language.

rjmccall fucked around with this message at 09:03 on Nov 5, 2009

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got a string with an HTML snippet in it. I need a List of innerHTML for all the table cell elements. A regexp seems like the right tool, I'm just horrible at it. Can anybody help me out?

monads mo problems
Nov 27, 2007

yatagan posted:

I don't know but it's painful to try to decipher. This is a recursive Fibonacci sequence:

code:
public int doFib(int x) {
  if (x <= 0) {
    return 0;
  } else if (x == 1) {
    return 1;
  } else {
    return doFib(x-1) + doFib(x-2);
  }
}

Or if you care about efficiency:
code:
public static int doFib(int x) {
  if (x <= 0) return 0;
  if (x == 1) return 1;
  return doFibHelper(x - 2, 1, 1);
}

private static int doFibHelper(int x, int a1, int a2) {
  if (x == 0) return a1 + a2;
  return doFibHelper(x - 1, a1 + a2, a1);
}

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

Steell posted:

Or if you care about efficiency:
code:
public static int doFib(int x) {
  if (x <= 0) return 0;
  if (x == 1) return 1;
  return doFibHelper(x - 2, 1, 1);
}

private static int doFibHelper(int x, int a1, int a2) {
  if (x == 0) return a1 + a2;
  return doFibHelper(x - 1, a1 + a2, a1);
}

There are easier ways to improve on the efficiency of a naive recursive fib() implementation

yatagan
Aug 31, 2009

by Ozma

Otto Skorzeny posted:

There are easier ways to improve on the efficiency of a naive recursive fib() implementation

Like implementing it iteratively, or what did you have in mind? It's been a while since I've needed to optimize recursion.

Save the whales
Aug 31, 2004

by T. Finn

fletcher posted:

I've got a string with an HTML snippet in it. I need a List of innerHTML for all the table cell elements. A regexp seems like the right tool, I'm just horrible at it. Can anybody help me out?

Like this?

code:
String html = "<table><tr><td><a href=\"#\">foo</a><span>bar</span></td><td><div>baz</div></td></tr></table>";
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(?<=<td>).*?(?=</td>)").matcher(html);
while (m.find()) System.out.println(m.group());
I find this serves as a good reference for regex syntax: http://www.regular-expressions.info/reference.html

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Save the whales posted:

Like this?

code:
String html = "<table><tr><td><a href=\"#\">foo</a><span>bar</span></td><td><div>baz</div></td></tr></table>";
java.util.regex.Matcher m = java.util.regex.Pattern.compile("(?<=<td>).*?(?=</td>)").matcher(html);
while (m.find()) System.out.println(m.group());
I find this serves as a good reference for regex syntax: http://www.regular-expressions.info/reference.html

Doesn't seem to work when the cell has an attribute: <td onclick="what()"></td>

epswing
Nov 4, 2003

Soiled Meat

fletcher posted:

I've got a string with an HTML snippet in it. I need a List of innerHTML for all the table cell elements. A regexp seems like the right tool, I'm just horrible at it. Can anybody help me out?
code:
import java.io.ByteArrayInputStream;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

public class InnerHtml {
	
	public static void main(String[] args) throws Exception {
		
		String html =
			"<table>" +
				"<tr>" +
					"<td>one</td><td>two</td><td>three</td>" +
				"</tr>" + 
				"<tr>" +
					"<td>four</td><td>five</td><td>six</td>" +
				"</tr>" +
			"</table>";
		
		String xpath = "//td";
		
		Document document = new SAXBuilder().build(new ByteArrayInputStream(html.getBytes()));
		List<Element> elements = XPath.newInstance(xpath).selectNodes(document);
		
		for (Element element : elements) {
			System.out.println(element.getTextTrim());
		}
	}
}
...prints...
code:
one
two
three
four
five
six
Ensure you have jdom and jaxen on the classpath.

epswing fucked around with this message at 08:31 on Nov 6, 2009

Save the whales
Aug 31, 2004

by T. Finn

fletcher posted:

Doesn't seem to work when the cell has an attribute: <td onclick="what()"></td>

Oh right it was searching for exactly <td>. Here's another one:

code:
String html = "<table><tr><td onclick=\"what()\"><a href=\"#\">foo</a><span>bar</span></td><td><div>baz</div></td></tr></table>";
java.util.regex.Matcher m = java.util.regex.Pattern.compile("<td.*?>.*?</td>").matcher(html);
while (m.find()) {
  String g = m.group();
  System.out.println(g.substring(g.indexOf('>') + 1, g.lastIndexOf('<')));
}
edit: it probably breaks on nested tables

Save the whales fucked around with this message at 08:46 on Nov 6, 2009

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
That is why you don't use regexes for parsing XML or HTML and instead do something like what epswing posted.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

epswing posted:

Ensure you have jdom and jaxen on the classpath.

Thanks to both of you guys for the help, but I think I'm gonna have to go with epswing's solution for this one! Thank you!

Volguus
Mar 3, 2009

fletcher posted:

Thanks to both of you guys for the help, but I think I'm gonna have to go with epswing's solution for this one! Thank you!

epswing's suggestion is perfect, if the HTML you get to parse is properly formatted.

Another suggestion would be to use a HTML parser (as opposed to an XML one), such as the one in the JDK : http://java.sun.com/javase/7/docs/api/javax/swing/text/html/parser/Parser.html
That one is a bit more forgiving.

Or a 3rd party library, like http://htmlparser.sourceforge.net/

zootm
Aug 8, 2006

We used to be better friends.

rhag posted:

epswing's suggestion is perfect, if the HTML you get to parse is properly formatted.

Another suggestion would be to use a HTML parser (as opposed to an XML one), such as the one in the JDK : http://java.sun.com/javase/7/docs/api/javax/swing/text/html/parser/Parser.html
That one is a bit more forgiving.

Or a 3rd party library, like http://htmlparser.sourceforge.net/
For what it's worth, the best HTML parsing/fixing library I've used for Java is TagSoup. Think it exposes a standard SAX interface too.

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane
Is there an easy way to create a Swing GUI (or part thereof) with overlapping components, but with as little absolute positioning as possible and greatest use of existing Swing widgets? Specifically, I'm working on a simple card game, and I want to have cards overlap nicely when displaying hands. If worst comes to worst, we can do everything manually, but it seems like this must be possible somehow, and doing it the "proper" way seems to me to be much less error-prone.

karuna
Oct 3, 2006
Hi, I have a question I'm having trouble understanding.

Using the class Buffer construct a pipeline of threads that will sort, in ascending order, a given list of numbers. Each thread in the chain receives the next number from its predecessor and chooses to keep it or pass it on. It keeps the value if it is less than its current value. To communicate the threads use an array of Buffer. The source of the data, i.e. the data generator, writes N items in turn to the first buffer in the chain. Each thread in the chain reads from its buffer waiting if necessary. When the sort is complete each thread should copy its number to a shared array.

code:
class Buffer{
	int x;
	boolean item; 
	public Buffer(){item = false;}
	synchronized int read(){
		while(!item){
			try{ wait(); }
			catch(InterruptedException e){}
		}
		item = false; int k = x;
		notify(); return k;
	}
	synchronized void write(int k){
		while(item){
			try{ wait(); }
			catch(InterruptedException e){}
		}
		x = k; item = true;
		notify();
	}
}
My idea for a solution:

Data generator (thread that just generates random ints to the first buffer)
Buffer[100]
100 Threads

Thread0 calls Buffer[0].read twice.
Thread0 writes the buffer with highest value to Buffer[1]

Thread1 calls Buffer[1].read

Following step is repeated N times.

Thread0 calls Buffer[0].read
Thread0 writes the buffer with highest value to Buffer[1]

Thread1 writes buffer with highest value to Buffer[2]

Thread2 calls Buffer[2].read

etc..

From the question am I on the right track?


Once Thread0 has nothing left to read, the random ints will be sorted.
Each Thread will then write to a result[]
Thread0 writes its value to result[0] and so on.

Max Facetime
Apr 18, 2009

PT6A posted:

Is there an easy way to create a Swing GUI (or part thereof) with overlapping components, but with as little absolute positioning as possible and greatest use of existing Swing widgets? Specifically, I'm working on a simple card game, and I want to have cards overlap nicely when displaying hands.

I haven't used Swing much, but that doesn't sound like something Swing is intended for. Maybe use JavaFX for drawing the card game and Swing around it for GUI?

HFX
Nov 29, 2004

PT6A posted:

Is there an easy way to create a Swing GUI (or part thereof) with overlapping components, but with as little absolute positioning as possible and greatest use of existing Swing widgets? Specifically, I'm working on a simple card game, and I want to have cards overlap nicely when displaying hands. If worst comes to worst, we can do everything manually, but it seems like this must be possible somehow, and doing it the "proper" way seems to me to be much less error-prone.

Swing at the high level is not a graphics library. It is a platform windowing toolkit (as is the awt upon which swing is built, and swt). Specifically, it was designed so you could have consistent theme across multiple platforms. However, you do have access to basic image rotation, scaling, etc provided through the underlying awt. You would copy the rotated image onto a general image. If you are looking for something more, then you will need to look at JavaFX.

Foran
Apr 19, 2008

Garry's Mod is an Art
I'm making a tile-based game, and I'm a little confused on this:
I have an array for my map, and I have a tile system. A Tile has numerous values, like pollution, power, type, etc. How do I tell the system what part of the array is what kind of tile, and what the values in that specific tile in that part of the array are?

also, just to clarify, Tile is a class.

Foran fucked around with this message at 03:34 on Nov 8, 2009

1337JiveTurkey
Feb 17, 2005

Rsugar posted:

I'm making a tile-based game, and I'm a little confused on this:
I have an array for my map, and I have a tile system. A Tile has numerous values, like pollution, power, type, etc. How do I tell the system what part of the array is what kind of tile, and what the values in that specific tile in that part of the array are?

You can just make a Tile object which has the appropriate getters and setters for the basic attributes. Tile-specific behavior can be handled through subclassing. Then just stick them into your array and just look it up using the coordinates when you need them.

edit: Are you having trouble with array lookups?

Foran
Apr 19, 2008

Garry's Mod is an Art

1337JiveTurkey posted:

You can just make a Tile object which has the appropriate getters and setters for the basic attributes. Tile-specific behavior can be handled through subclassing. Then just stick them into your array and just look it up using the coordinates when you need them.

edit: Are you having trouble with array lookups?

ah, gently caress. No, I was just thinking too hard. I've done this all before, and in c++, but I've been reading through java books all day and haven't really allowed all of it to process. Thanks though, that is what I was I was looking for.

Used Car Salesman
Apr 2, 2007
and his DOG SPOT!
This is some sort of hosed up cross-post post type question which is neither purely C nor Java related.

I'm intermediate with Java, and barely a beginner with C.

I've been playing with JNA, trying to use the WinAPI examples to access the icons on my desktop. ( I want the positions, names, path, and iconimage of each icon on the desktop as part of an larger project.)

I found an old-ish C program which does most of what I want, and have been attempting to port it to Java. I'm using JNA to do the Windows API calls. I apparently need to use shared memory with my Explorer process to read the positions of the icons.

My difficulty arises in trying to port the statements:
code:
       ipc_iconpos = AllocMemInForeignProcess(explorer, sizeof(POINT));
       ipc_iconlabel = AllocMemInForeignProcess(explorer, sizeof(LVITEM));

....

       private Pointer AllocMemInForeignProcess(W32API.HANDLE process, long size) throws Win32NullException {
       Pointer pointer;
       pointer = Kernel32.INSTANCE.VirtualAllocEx(process, null, size, Kernel32.MEM_COMMIT, Kernel32.PAGE_READWRITE);
       if (pointer == null) {throw new Win32NullException("AllocMemInForeignProcess() failed. NULL pointer returned.");}
       return pointer;
    }

I believe POINT is described in Windows.h and I looked at the MSDN article on LVITEM but couldn't make heads or tails of it.

What is the sizeof() of an LVITEM or POINT? I'm assuming I only need to know this so I don't walk over into other areas of memory? Can I get away with using some unholy huge int, or would that only gently caress me up further?

What C/C++ library would I find sizeof() if LVITEM's size is ambiguous?
Does JNA have some sort of example of the sizeof() function ported to Java and how it might be applied here?

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip
operator sizeof is not a function

Foran
Apr 19, 2008

Garry's Mod is an Art
Ok, so back to another problem, terrain generation. My game works in similar form to Sim City 4, in that there is a large World(region in sc4) map, comprised of tiles containing City maps. I know that I can use fractals to generate height-maps, but how can I take that height map (which is converted into an array of a sequence of numbers, i.e. a number 1 in the array designates a water tile, 2 a grass tile, etc.), and then from the resulting tiles, generate terrain based upon that tile to fill the city map?

keep in mind that adjacent city maps should probably conform to neighboring city maps...

Foran fucked around with this message at 00:26 on Nov 9, 2009

BATH TUB
Jun 27, 2003
I have an interview on Thursday for an internship wherein I would be writing Java.

Now, they're looking for somebody at a junior level so they probably don't expect me to have much more experience than an undergraduate algorithms class, basic principles of software development, and data structures -- all of which I'm totally confident in and I have no worries about my ability to interview confidently based on them.

On the other hand, my knowledge of Java goes about as far as implementing a binary search tree. 99.98% of my programming experience is in C++, which I'm definitely intermediate level with.

Is there some "Java for retards who happen to know C++ pretty well" website? I just need something I can read in an afternoon that tells me "X feature in Java is really Y feature in C++" so if I get Java-specific questions like "when would you use a java beans AWT noun noun noun" I can answer them without looking like a horrible moron.

1337JiveTurkey
Feb 17, 2005

timecircuits posted:

I have an interview on Thursday for an internship wherein I would be writing Java.

Now, they're looking for somebody at a junior level so they probably don't expect me to have much more experience than an undergraduate algorithms class, basic principles of software development, and data structures -- all of which I'm totally confident in and I have no worries about my ability to interview confidently based on them.

On the other hand, my knowledge of Java goes about as far as implementing a binary search tree. 99.98% of my programming experience is in C++, which I'm definitely intermediate level with.

Is there some "Java for retards who happen to know C++ pretty well" website? I just need something I can read in an afternoon that tells me "X feature in Java is really Y feature in C++" so if I get Java-specific questions like "when would you use a java beans AWT noun noun noun" I can answer them without looking like a horrible moron.

Java is significantly different from C++ in how it's used so it's hard to just give a 1:1 mapping beyond libraries like SAX or OpenGL/JOGL. The official tutorials keep the basic language syntax to one section of one tutorial so you can just skip the stuff on basic flow control. You'll probably want to understand how Java handles exceptions differently as well as how it handles inheritance but those are both less complex than C++. The tutorials also cover a lot of the basic libraries that you'll want to know. Focus on having a solid understanding of the basics and don't worry about the more complex APIs. There's always the risk that you'll run into some insane interviewer who considers knowing how to diagnose bizarre classpath issues running WAS 6.1 on Solaris to be fair game but you can't plan for every contingency. On the other hand it's much more likely that they'll want someone who understands the difference between a List<String>, a LinkedList<String> and an ArrayList<String> and which can be used in place of which.

BATH TUB
Jun 27, 2003

1337JiveTurkey posted:

Java is significantly different from C++ in how it's used so it's hard to just give a 1:1 mapping beyond libraries like SAX or OpenGL/JOGL. The official tutorials keep the basic language syntax to one section of one tutorial so you can just skip the stuff on basic flow control. You'll probably want to understand how Java handles exceptions differently as well as how it handles inheritance but those are both less complex than C++. The tutorials also cover a lot of the basic libraries that you'll want to know. Focus on having a solid understanding of the basics and don't worry about the more complex APIs. There's always the risk that you'll run into some insane interviewer who considers knowing how to diagnose bizarre classpath issues running WAS 6.1 on Solaris to be fair game but you can't plan for every contingency. On the other hand it's much more likely that they'll want someone who understands the difference between a List<String>, a LinkedList<String> and an ArrayList<String> and which can be used in place of which.

Thanks, this is exactly what I was looking for!

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I was going to say that I've never found a use for a LinkedList over an ArrayList, but then I remembered that it implements the queue and deque interfaces.

1337JiveTurkey
Feb 17, 2005

MEAT TREAT posted:

I was going to say that I've never found a use for a LinkedList over an ArrayList, but then I remembered that it implements the queue and deque interfaces.

It's also good for data structures 1 homework where your professor thinks your name is Josh Bloch.

HFX
Nov 29, 2004

MEAT TREAT posted:

I was going to say that I've never found a use for a LinkedList over an ArrayList, but then I remembered that it implements the queue and deque interfaces.

I'm just the opposite and tend to use LinkedList more. However, a lot of my work involves queues and processing huge collections at once with additions only at the end. Might also be a bit of my functional programming creeping in. I usually find HashMap or TreeMap to be my goto data structures though.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
I generally use a LinkedList by default and switch to an ArrayList when I know I'll need efficient random access. I mostly use a List for iteration, so a LinkedList works just as well.

I usually specify variables and parameters as a List, except when using Swing to draw a GUI. I don't know this for sure, but I think a JTable needs random access, so in my Swing GUI code, I have a variable specified as an ArrayList to keep me from accidentally putting a LinkedList in it.

Brain Candy
May 18, 2006

Unless you are using large lists (say 20000+), an ArrayList will be faster and allows constant time random access. If you only need to use the Deque interface, why not just use an ArrayDeque? Hell, if you only use List for iteration, just use Collection.

Adbot
ADBOT LOVES YOU

Fly
Nov 3, 2002

moral compass

Brain Candy posted:

Hell, if you only use List for iteration, just use Collection.
Collection is only an interface, so it does not really address the question of which type to instantiate.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply