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
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

BELL END posted:

You'd probably have to cast one or both of the variables as a double for it to return a double, this should work with Java5 or later.

I want it to return an ArrayList of Doubles, aggregatedPoints and dataSetSum are both ArrayList<Double>'s

Adbot
ADBOT LOVES YOU

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

I don't think you can have overloaded operators in Java.

zootm
Aug 8, 2006

We used to be better friends.
You're right, BeefofAges, Java doesn't have operator overloading.

poopiehead
Oct 6, 2004

Am I missing something here? Just want to see if I'm missing something obvious. This is an excerpt of a non-blocking queue implementation.

code:
public class LinkedQueue <E> {
    private static class Node <E> {
        final E item;
        final AtomicReference<Node<E>> next;

        Node(E item, Node<E> next) {
            this.item = item;
            this.next = new AtomicReference<Node<E>>(next);
        }
    }

    private AtomicReference<Node<E>> head
        = new AtomicReference<Node<E>>(new Node<E>(null, null));
    private AtomicReference<Node<E>> tail = head;

    public boolean put(E item) {
        Node<E> newNode = new Node<E>(item, null);
        while (true) {
            Node<E> curTail = tail.get();
            Node<E> residue = curTail.next.get();
            if (curTail == tail.get()) {
                if (residue == null) /* A */ {
                    if (curTail.next.compareAndSet(null, newNode)) /* C */ {
                        tail.compareAndSet(curTail, newNode) /* D */ ;
                        return true;
                    }
                } else {
                    tail.compareAndSet(curTail, residue) /* B */;
                }
            }
        }
    }
}
When they assign tail = head, that's a bug right? When you call tail.compareAndSet() it's going to affect head.get() as well.

I know this is basic java, but I doubt myself when it's in an article by Brian Goetz on a popular site and written 2 years ago.

zootm
Aug 8, 2006

We used to be better friends.
This all seems extremely complicated, but the implementation looks at least mostly correct - the paper in question is here. Concurrent algorithms are something of a black art and I this is currently hurting my head.

You could be correct though, it might be that head should be written as an atomic reference to the same node as tail rather than being the same atomic reference. Not sure, though. The line in the paper there is:
code:
Q–>Head = Q–>Tail = node
If Head and Tail are both supposed to be independent atomic references to "node", that would tally better with them each being a separate AtomicReference instance.

Edit: The implementation given is consistent with (not the same as, but consistent with) the one in OpenJDK. :psyduck:

zootm fucked around with this message at 11:18 on Jun 21, 2008

poopiehead
Oct 6, 2004

Thanks for confirming that I'm not crazy.

The OpdenJDK implementation looks ok. tail and head are volatile read-only fields. They use this special atomic reference class that handles all of the writes to the fields using reflection. Hopefully that makes you feel better ;)

zootm
Aug 8, 2006

We used to be better friends.

poopiehead posted:

The OpdenJDK implementation looks ok. tail and head are volatile read-only fields. They use this special atomic reference class that handles all of the writes to the fields using reflection. Hopefully that makes you feel better ;)
When I was looking at the OpenJDK one, it looked a lot like both head and tail fields were initialised to the same container instance, and the container instances used the reflection thing to update their "next" and "item" fields. Confusing anyway!

poopiehead
Oct 6, 2004

zootm posted:

When I was looking at the OpenJDK one, it looked a lot like both head and tail fields were initialised to the same container instance, and the container instances used the reflection thing to update their "next" and "item" fields. Confusing anyway!

Yeah it's weird. too lazy to copy and paste, but it was like this, more or less....

code:
private volatile Node head = new Node(null,null);
private volatile Node tail = head;

private headUpdater = new AtomicUpdatingReferenceThing("head")
private tailUpdate = new AtomicUpdatingReferenceThing("tail");
Then for reads, they just went directly at the Nodes, for writes, they go through the updaters.

zootm
Aug 8, 2006

We used to be better friends.
That's not what I thought I read at all! I'll need to check up on that again. Neat, anyway.

Ramzi
Oct 10, 2004
The inner child of my soul was repeatedly gangbanged by a team of mall Santas.
Does anyone know a good JAVA API for creating card games? Basically, I don't want to have to create the graphics for all 52 cards myself, nor do I want to program common card game animations. Like placing cards on top of each other horizontally or vertically, selecting cards, moving piles of cards at a time, etc. I just want to code the logic of the game.

Entheogen
Aug 30, 2004

by Fragmaster

Ramzi posted:

Does anyone know a good JAVA API for creating card games? Basically, I don't want to have to create the graphics for all 52 cards myself, nor do I want to program common card game animations. Like placing cards on top of each other horizontally or vertically, selecting cards, moving piles of cards at a time, etc. I just want to code the logic of the game.

dunno, but you could just use Java2D to make that API yourself. The hardest part would probably be creating the card graphics.

Gousgounis
Jan 22, 2008

Ramzi posted:

Does anyone know a good JAVA API for creating card games? Basically, I don't want to have to create the graphics for all 52 cards myself, nor do I want to program common card game animations. Like placing cards on top of each other horizontally or vertically, selecting cards, moving piles of cards at a time, etc. I just want to code the logic of the game.

Edit: I read your post more carefully if you don't want to do everything from scratch just google "java card game source code" or some variation. I just did and found a ton of relevant hits, from applets, to desktop apps and straight up java code.

I started on that a while back but have shelved the phoject until life is a little less hectic.
I will need to dig up that project and see what I used but the graphics api is a good starting point:

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics.html

Here is the 2D api like Entheogen said:

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html

Start from there, but there are a ton others dealing with image manipulation, colors, etc, etc...

Gousgounis fucked around with this message at 23:15 on Jun 24, 2008

Entheogen
Aug 30, 2004

by Fragmaster
I am parsing a binary files that is full of 4-byte floating point numbers. But for some reason my Java program reads in floats wrong, as they jump all over the range spectrum, while I know that they are only supposed to be between 0 and 5.

This leads me to believe that this is an endianess problem. Is there a quick and dirty way to take a float type in java and "reverse" it? Or would I have to read in the bytes, reverse them myself and then put them into int and then parse the bits into a float?

By the way FORTRAN 77 reads this same file fine. It is supposed to be FORTRAN's Real format. Shouldn't it be all same IEEE standard though?

Leehro
Feb 20, 2003

"It's a gaming ship."
How are you building the floats?

2 things to keep in mind

1. If you do any kind of byte addition or arithmetic, they will be sign-extended to integers. If you have Byte b, use b & 0xFF in arithmetic operations.

2. I wrote some code to read some image data out of a proprietary format, and mostly used ByteBuffer objects to get the int/float data from the header, especially because I needed to be able to set the Endian-ness.

http://java.sun.com/j2se/1.4.2/docs/api/java/nio/ByteBuffer.html

Entheogen
Aug 30, 2004

by Fragmaster
solved this using this class: http://www.unidata.ucar.edu/software/netcdf-java/v2.2.22/javadoc/ucar/unidata/io/Swap.html

zootm
Aug 8, 2006

We used to be better friends.
I think the ByteBuffer solution is the "correct" one here, but if that Swap thing works for you and it's a small project then I suppose you may as well.

Entheogen
Aug 30, 2004

by Fragmaster

zootm posted:

I think the ByteBuffer solution is the "correct" one here, but if that Swap thing works for you and it's a small project then I suppose you may as well.

I'll definetly remember about bytebuffer for future reference, but in this case it was far easier to use Swap method, because I already had a simple function to read in floats from binary file, so I just wanted a method to take in a float and retrun "reversed" float.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
If I'm writing a function that looks like:

code:
private LinkedHashMap<String, LinkedHashMap<String, Double>> getTerritoryTimeOff(Connection connection, GetUserInfoResult user, 
			HashMap<String, HashMap<String, String>> syncInfo, Integer scale, Boolean isSummary) {}
am I necessarily doing something wrong or designing this poorly? Is there something I should think about to make it simpler or is this already pretty simple? this function basically builds a SQL query, executes it, and returns the results.

Entheogen
Aug 30, 2004

by Fragmaster

fletcher posted:

If I'm writing a function that looks like:

code:
private LinkedHashMap<String, LinkedHashMap<String, Double>> getTerritoryTimeOff(Connection connection, GetUserInfoResult user, 
			HashMap<String, HashMap<String, String>> syncInfo, Integer scale, Boolean isSummary) {}
am I necessarily doing something wrong or designing this poorly? Is there something I should think about to make it simpler or is this already pretty simple? this function basically builds a SQL query, executes it, and returns the results.

make your own class that encapsulates results of the query and return ArrayList< query_encapsulation_class >

you could probably do the same for syncInfo.

Also check if there are already classes out there in the standard API or the libraries you are using that already encapsulate the info you are dealing with here.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Entheogen posted:

make your own class that encapsulates results of the query and return ArrayList< query_encapsulation_class >

you could probably do the same for syncInfo.

Also check if there are already classes out there in the standard API or the libraries you are using that already encapsulate the info you are dealing with here.

Could you elaborate a little more? I'm a bit confused on your explanation.

Do you mean doing something like:

SyncInfo syncInfo, instead of having it be a HashMap<String, HashMap<String, String>> and put some logical methods for accessing the content of it? What about with the query results?

fletcher fucked around with this message at 01:29 on Jun 26, 2008

Entheogen
Aug 30, 2004

by Fragmaster

fletcher posted:

Could you elaborate a little more? I'm a bit confused on your explanation.

well encapsulation pretty much means that you write a container class to deal with whatever data/entity you are working with.

so instead of having this: LinkedHashMap<String, LinkedHashMap<String, Double>>

you can have class that contains that as private variable and has accessor/modifier functions as well as some other methods for it.

Also think about the actual data structure that you need to contain your results. Is hash map the best way? or is there something more simple? Not saying that Linked Hash map is the wrong thing, but if you had a method like queryResult that encapsulated all of your results then you could change the internal data structure from LinkedHashMap to something better, if you so choose, later on.

Pretty much what this means is make a new class to deal with complexity as much as you can whenever it makes good sense.

quote:


Do you mean doing something like:

SyncInfo syncInfo, instead of having it be a HashMap<String, HashMap<String, String>> and put some logical methods for accessing the content of it? What about with the query results?

Exactly. Sorry if my explanation is convoluted, I have been doing java all freaking day long :(

Alan Greenspan
Jun 17, 2001

Eclipse configuration question: I have this

code:
public interface IInterface
{
  /**
  * Some incredibly useful comment.
  **/
  void foo();
}

public class MyClass implements IInterface
{
  @Override
  public void foo()
  {
    // Code goes here.
  }
}
What I want now is that Eclipse mirrors the incredibly useful comment so that I can see it right above the implementation of the foo function in MyClass. Basically I want comments from interfaces visible above implementing methods in classes. Is this possible?

Also: I want these comments to be visible directly in the source, not the Javadoc tab.

Entheogen
Aug 30, 2004

by Fragmaster

Alan Greenspan posted:

Eclipse configuration question: I have this

code:
public interface IInterface
{
  /**
  * Some incredibly useful comment.
  **/
  void foo();
}

public class MyClass implements IInterface
{
  @Override
  public void foo()
  {
    // Code goes here.
  }
}
What I want now is that Eclipse mirrors the incredibly useful comment so that I can see it right above the implementation of the foo function in MyClass. Basically I want comments from interfaces visible above implementing methods in classes. Is this possible?

Also: I want these comments to be visible directly in the source, not the Javadoc tab.

I don't know about Eclipse but in JBuilder when you create a class and tell it to implement an interface, it automatically inserts comments from those interface functions as well as write empty bodies.

Perhaps there is an option in Eclipse to also add a new method to class and tell it that it is from some interface, and that should also copy/paste comments.

csammis
Aug 26, 2003

Mental Institution

Entheogen posted:

Perhaps there is an option in Eclipse to also add a new method to class and tell it that it is from some interface, and that should also copy/paste comments.

When you tell Eclipse to implement an interface, @see Javadoc tags are inserted that reference the interface, but it doesn't put in the comments verbatim. Alt+Shift+J on the method does the same thing.

Also why are you using @Override on an interface method?

zootm
Aug 8, 2006

We used to be better friends.

csammis posted:

Also why are you using @Override on an interface method?
Eclipse does it by default, warns if you don't, and it's as useful there as anywhere :)

Entheogen
Aug 30, 2004

by Fragmaster
why do you need @Override anyway? I never used it, and never got any warnings from javac compiler.

Seems like it is something pretty trivial.

Sharrow
Aug 20, 2007

So... mediocre.
Does Java have a simple, hands-off date parsing function like Ruby's Date.parse, which will construct a date out of just about any slightly-recognisable string?

I'm doing some maintenance on an EJB 3 application, and there's a part of it that's returning dates in mixtures of RFC 3339, RFC 822, ISO 8601, and some other bizarre ways. The underlying data is all the same, and I can't see what's producing the differences, so I hoped I could skip over it and just reparse them all.

java.text.DateFormat is just a big wtf though.

Edit: JDK 1.5.0_15.

Sharrow fucked around with this message at 20:19 on Jun 26, 2008

necrobobsledder
Mar 21, 2005
Lay down your soul to the gods rock 'n roll
Nap Ghost
Is there any way to create localizable annotations? The problem with annotations to me is that they're embedded in with the class and can't be localized easily. It's kind of a bitch having to use resource bundles at the moment to basically duplicate my comments in code externally, and I see myself repeating things a lot such that I'd rather just have a reference to a resourcebundle property within my annotations. I don't want to write property files any more, mommy :(

clayburn
Mar 6, 2007

Cammy Cam Juice
I've never really used done any sort of GUI stuff before, but I am currently trying to implement some Swing stuff using NetBeans GUI Builder. I have two problems that I can't seem to figure out. Basically I want to browse file much like the Windows Explorer does. I want a file tree on the left column with the detailed list view using the rest of the window. I can not figure out how to get the JTree to point to the file structure or how to make sortable columns in a JList. Is there some easy way to do either of these things or am I going to have to hack something together?

Entheogen
Aug 30, 2004

by Fragmaster

clayburn posted:

I've never really used done any sort of GUI stuff before, but I am currently trying to implement some Swing stuff using NetBeans GUI Builder. I have two problems that I can't seem to figure out. Basically I want to browse file much like the Windows Explorer does. I want a file tree on the left column with the detailed list view using the rest of the window. I can not figure out how to get the JTree to point to the file structure or how to make sortable columns in a JList. Is there some easy way to do either of these things or am I going to have to hack something together?

Suggestion. Don't use GUI builder when learning Swing. Do everything by code. You will learn much better that way and have more control over what is done.

As far as JTree and JList goes, it probably involves overloading them, and adding some custom DataModels. I have never used them, but I have used Swing a lot before, and overloaded JTable's stuff, so I imagine this works similar.

Here is a link to get you started: http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html#data

As for making JTree do folder view, you probably want to overload that DataModel and use File to get folder structure and list of files.

Entheogen fucked around with this message at 00:08 on Jun 27, 2008

poopiehead
Oct 6, 2004

Entheogen posted:

why do you need @Override anyway? I never used it, and never got any warnings from javac compiler.

Seems like it is something pretty trivial.

For one thing, it prevents you from changing the signature of a method that was meant to override another. Prevents you from doing something like changing your toString() method to toString(String formatString). Your code will compile fine without it, but it's a useful tool. It also makes the code more readable because you know at a glance that it is overriding.

In C#, it's even part of the method signature.

On using @Override with interfaces, it will actually cause a compiler error in Java 5, but will not in Java 6.

poopiehead fucked around with this message at 01:20 on Jun 27, 2008

zootm
Aug 8, 2006

We used to be better friends.

poopiehead posted:

In C#, it's even part of the method signature.
In C# the keyword does actually mean something, though; in Java it's not required mostly because it's just a check, as you say. It is very useful in the cases that you note.

poopiehead posted:

On using @Override with interfaces, it will actually cause a compiler error in Java 5, but will not in Java 6.
Yeah, I think that's why people are surprised to see it.

Alan Greenspan
Jun 17, 2001

csammis posted:

Also why are you using @Override on an interface method?

Pretty much what the others said. My Eclipse adds it automatically and it's cool because unintended interface changes often turn into compilation errors.

Also: Too bad that what I want does apparently not exist in Eclipse. :saddowns:

shodanjr_gr
Nov 20, 2007
I am having an issue with some cryptography stuff in java.

I am using a Message Authentication Code generator to produce MD5 hashes for some packets.

The Mac class can be initialized using a SecretKey object. My issue is that i can not find a way to produce such a SecretKey, based on an integer or a string or something that two users can exchange before hand...

I thought about using the SecretKeyFactory method translateKey to produce a compatible key based on an SecretKeySpec (which allows for the user to set a byte array as the key), but i cant get an instance of SecretKeyFactory for the HmacMD5 algorithm...

Any ideas?

Also, please let me know if the above makes no sense...

edit:

Since i found a solution, i might as well post it here. If anyone has the same issue, check out PBE (password based encryption).

shodanjr_gr fucked around with this message at 20:00 on Jun 28, 2008

Cagado Anarquista
Feb 17, 2007
escravo do lastcaress
Hi guys, I'm having some memory problems with java. I'm currently writing some code that needs lots of memory (heap). So, in order to avoid the out of memory exception, I tried launching my eclipse with

-vmargs -Xms<val>m -Xmx<val>m

I have tried several combinations with the <val> (256, 512, 1024, etc) but I cannot seem to get more than 64m available to me! I can't understand why! A simple new double[1000][10000] will explode because it doesn't have enough memory.

I've also played around with the -Xss but that didn't help either.

Anyone know why/how to solve this?

Thanks in advance.

zootm
Aug 8, 2006

We used to be better friends.
Changing the command line arguments only changes the memory available to Eclipse itself; your program runs in a completely separate VM. You can manage this from within Eclipse. One way to do it is in Preferences, go to Java/Installed JREs, "Edit..." the one you use, and then put args in "default VM arguments". You can also do it on a per-launch configuration basis by playing with them in your project settings.

Cagado Anarquista
Feb 17, 2007
escravo do lastcaress

zootm posted:

Changing the command line arguments only changes the memory available to Eclipse itself; your program runs in a completely separate VM. You can manage this from within Eclipse. One way to do it is in Preferences, go to Java/Installed JREs, "Edit..." the one you use, and then put args in "default VM arguments". You can also do it on a per-launch configuration basis by playing with them in your project settings.

Thanks, that worked!

epswing
Nov 4, 2003

Soiled Meat
I'm curious, what are you using a new double[1000][10000] for?

Alan Greenspan
Jun 17, 2001

I have like 50-75 classes that need to have the same 9 lines:

code:
private ListenerProvider<T> listeners = new ListenerProvider<T>();

public void addListener(T listener)
{
  listeners.addListener(listener);
}

public void removeListener(T listener)
{
  listeners.removeListener(listener);
}
where T needs to be a concrete but variable type.

Is there any way that I can auto-generate these lines of code. I'd really like to do:

code:
@AddListener(MyListenerType)
public class Whatever
{
}
Also: the listeners variable must be accessible from regular code.

I'm using Eclipse. apt looks like it might work. Anybody ever done anything like that?

Adbot
ADBOT LOVES YOU

Cagado Anarquista
Feb 17, 2007
escravo do lastcaress

epswing posted:

I'm curious, what are you using a new double[1000][10000] for?

I'm doing some matrix computations (more specifically, SVD) using the JAMA library. It's a very sparse matrix (document-feature matrix) and I would love to use some better representation to save memory (only positive elements), but I can't really rewrite the math needed.

Know any better way?

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