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
Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
src/main/resources

Adbot
ADBOT LOVES YOU

Coca Koala
Nov 28, 2005

ongoing nowhere
College Slice
I want to be able to compare two strings and see if they have the same contents, ignoring order. So "ABC" is the same as "CAB", but different from "AAB" which equals "ABA".

It looks like a good way to do it is to turn each string into a character array, then turn the arrays into linked lists. Once I have the lists, I can look at the element in index i in list A, and remove the first instance of that element in list B. If I find an element in A that isn't in B, the lists aren't equal. If I go all the way through list A and list B still contains at least one element, the lists aren't equal.

I can look through the list just fine with a for loop, but I'm having trouble working with .get(index i) and .remove(object o).

code:
for (int i = 0; i < length; i++)
		{
			Object E = AL.get(i);
			
			System.out.println(E+" "+i);
			BL.remove(E);
		}
I put in the System.out bit to see what was going on, and java tells me that E is "[C@10d448", no matter what it's actually looking at in the list. I've never actually worked with lists before, so I don't know precisely what I'm supposed to be doing.

Is there a better way to do what I want to do? And how do I properly compare elements between two lists?

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right

Coca Koala posted:

I want to be able to compare two strings and see if they have the same contents, ignoring order. So "ABC" is the same as "CAB", but different from "AAB" which equals "ABA".

I'm pretty new to Java, but I'm pretty sure you need to cast there.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
One way to do that easily could be to either sort the characters of the strings and ensure that they're equal or, as I have done, to dump the characters into hashsets and take advantage of the semantics of their equals() method.
code:
HashSet<Character> charSet(String a) {
  HashSet<Character> ret = new HashSet<Character>();
  for(char c : a.toCharArray()) { ret.add(c); }
  return ret;
}

boolean sameChars(String a, String b) {
  return charSet(a).equals(charSet(b));
}
I wholeheartedly admit that this is somewhat deranged.

Edit: woah, no- this isn't quite right. Sets will collapse multiple copies of the same letter. What was I thinking? Here's a different approach similar to the original description:
code:
boolean sameChars(String a, String b) {
  List<Character> tmp = new ArrayList<Character>();
  for(Character c : a.toCharArray()) { tmp.add(c); }
  for(Character c : b.toCharArray()) { if (!tmp.remove(c)) { return false; } }
  return tmp.size() == 0;
}

Internet Janitor fucked around with this message at 04:01 on Jan 13, 2012

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
If you replace the HashSet with a HashMap, and replace inserting with "insert or increment", it works.

Max Facetime
Apr 18, 2009

Since that sounds like a homework problem and the most important point was already made (that strings are not very good data structures for this problem), I'm going to nitpick a bit about case-insensitivity.

German is a wonderful language. It was only 4 years ago that Unicode added ẞ as the capital ß, but according to the German Wikipedia the Council for German orthography says that sharp s doesn't have a majuscule at all.

So what should the result of the comparison be right now and, if in a few years the Council changes their mind and the Java library is updated, should the result of the comparison change?

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Coca Koala posted:

I put in the System.out bit to see what was going on, and java tells me that E is "[C@10d448", no matter what it's actually looking at in the list.
There's a space char in your println statement, but no space in that output. Are you sure that's what the output is?

Also, putting raw arrays in Collections and using remove(Object) is generally a bad idea since arrays use the standard equals method, that is, the references must be equal.

Sereri
Sep 30, 2008

awwwrigami

I am in posted:

Since that sounds like a homework problem and the most important point was already made (that strings are not very good data structures for this problem), I'm going to nitpick a bit about case-insensitivity.

German is a wonderful language. It was only 4 years ago that Unicode added ẞ as the capital ß, but according to the German Wikipedia the Council for German orthography says that sharp s doesn't have a majuscule at all.

So what should the result of the comparison be right now and, if in a few years the Council changes their mind and the Java library is updated, should the result of the comparison change?

To be fair, a capital ß has never existed and might as well never will. The only use is in words written entirely in capitals and even then you either write ß or SS.

Max Facetime
Apr 18, 2009

Sereri posted:

To be fair, a capital ©¬ has never existed and might as well never will. The only use is in words written entirely in capitals and even then you either write ©¬ or SS.

I get the wibe from Wikipedia that it's because nobody can agree on what it should look like. Or like Wikipedia puts it:


ß
From Wikipedia, the free encyclopedia
   (Redirected from Sharp s)

Not to be confused with its capital form, ẞ, the Latin letter B, or the Greek letter β (beta).



I'm no expert on this subject which gives me plenty of justification to just throw up my hands and give up.

Coca Koala
Nov 28, 2005

ongoing nowhere
College Slice

Aleksei Vasiliev posted:

There's a space char in your println statement, but no space in that output. Are you sure that's what the output is?

Also, putting raw arrays in Collections and using remove(Object) is generally a bad idea since arrays use the standard equals method, that is, the references must be equal.

Yeah, the full output for that block is

code:
[C@10d448 0
[C@10d448 1
[C@10d448 2
So it's not returning the value of the space.

It doesn't look like what I'm trying to do will work anyways; even if I could get the lists to do what I need, I'd have to deal with over 200 million strings :sigh: Recursion is harder to code, but more efficient for this.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right
I created this code for Android. My question so far;

- is this optimal?
- can I get rid of that one final?
- for some reason the app crashes when the "OK!" button is clicked in the about dialog;

01-14 00:24:35.144: E/WindowManager(558): Activity com.grawl.faqplus.FAQPlusActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40521a70 that was originally added here
01-14 00:24:35.144: E/WindowManager(558): android.view.WindowLeaked: Activity com.grawl.faqplus.FAQPlusActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40521a70 that was originally added here

code:
package com.grawl.faqplus;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class FAQPlusActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Set up buttons
        
        Button buttonExit = (Button) findViewById(R.id.button_exit);
        Button buttonAbout = (Button) findViewById(R.id.button_about);
        
        // Set up AlertDialog for buttonAbout
        
        String aboutMessage = (String) getString(R.string.dialog_about);
        
    	AlertDialog.Builder builderAbout = new AlertDialog.Builder(this);
    	builderAbout.setMessage(aboutMessage);
    	builderAbout.setCancelable(false);
        builderAbout.setNeutralButton("OK!", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                 finish();
            }
        });
        final AlertDialog alertAbout = builderAbout.create();
        
        // Show about dialog
        
        buttonAbout.setOnClickListener(new OnClickListener() {
        	
            @Override
            public void onClick(View v) {
                alertAbout.show();
            }
        });
        
        // Exit app
                
        buttonExit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });      
        
    }
}

Grawl fucked around with this message at 00:26 on Jan 14, 2012

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
You're not actually cleaning up the about dialogue when you're done with it.

Calling finish() ends an entire Activity - something you probably don't want to do just because the user closed your About box. You never actually clean up the About box at all, so Android rightfully considers it leaked.

The correct way to remove and clean up a dialog is by calling dismiss() on it.

Sedro
Dec 31, 2008

Grawl posted:

- can I get rid of that one final?
No, Java can only close over final variables.

Personally, I try to make all fields/variables/parameters final. I'm curious, does this have any impact on performance?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Sedro posted:

Personally, I try to make all fields/variables/parameters final. I'm curious, does this have any impact on performance?

Assuming a sufficiently smart compiler (i.e. you're not developing for a Blackberry), I wouldn't think so.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right

Jabor posted:

The correct way to remove and clean up a dialog is by calling dismiss() on it.

Now I'm just confused, where do I call dismiss?

edit: I made it not crash by doing this (not calling finish()), but I doubt this is the right way;

code:
        // Set up AlertDialog for buttonAbout
        
        String aboutMessage = (String) getString(R.string.dialog_about);
        
    	AlertDialog.Builder builderAbout = new AlertDialog.Builder(this);
    	builderAbout.setMessage(aboutMessage);
    	builderAbout.setCancelable(false);
        builderAbout.setNeutralButton("OK!", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // finish();
            }
        });
        final AlertDialog alertAbout = builderAbout.create();
Just created an option to load another menu and go back, wonder if this is "proper" coding too;

code:
        // Open options menu
        
        buttonOptions.setOnClickListener(new OnClickListener() {
        	
        	@Override
        	public void onClick(View v) {
                Intent i = new Intent(FAQPlusActivity.this, FAQPlusOptions.class);
                startActivity(i);
                finish();
        	}
        });
(options class)

code:
        // Goto Main Menu
        
        buttonMainMenu.setOnClickListener(new OnClickListener() {
        	
        	@Override
        	public void onClick(View v) {
                Intent i = new Intent(FAQPlusOptions.this, FAQPlusActivity.class);
                startActivity(i);
                finish();
        	}
        });

Grawl fucked around with this message at 03:55 on Jan 14, 2012

Sedro
Dec 31, 2008

Jabor posted:

Assuming a sufficiently smart compiler (i.e. you're not developing for a Blackberry), I wouldn't think so.
I wouldn't think so either. I'm pretty sure final classes and methods have performance implications though, which is why I'm wondering. Does final always get translated to byte code, or is it just a compile-time tool? Can I use reflection to set the value of a final field?

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Grawl posted:

Now I'm just confused, where do I call dismiss?

You call dismiss when you want to close the dialogue and clean it up. Presumably when the user hits the OK button.

So instead of calling finish() (which closes the entire activity), you close just the dialog by calling dialog.dismiss().

Sedro posted:

I wouldn't think so either. I'm pretty sure final classes and methods have performance implications though, which is why I'm wondering. Does final always get translated to byte code, or is it just a compile-time tool? Can I use reflection to set the value of a final field?

It does get translated through to the bytecode, but it doesn't necessarily help in optimization - for example, the HotSpot JVM can determine whether a variable is ever written to (and optimize appropriately) even if you don't explicitly mark it as final.

1337JiveTurkey
Feb 17, 2005

Sedro posted:

Can I use reflection to set the value of a final field?

Yes if you call setAccessible(true) on the class to turn off that check. You still can't change the value of a static final field. In that particular case I believe that the javac compiler will bake compile-time constants into any class that actually references it, so it's prohibited.

Sedro
Dec 31, 2008

1337JiveTurkey posted:

In that particular case I believe that the javac compiler will bake compile-time constants into any class that actually references it, so it's prohibited.
Maybe it could for simple values, but now you have to recompile every class that depends on the constant if you ever change its value.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Sedro posted:

Maybe it could for simple values, but now you have to recompile every class that depends on the constant if you ever change its value.

I believe the compiler will fold constants inside a class entirely. Whereas if it's a constant referenced in another class, the folding is done by the jitter at class load time.

This is related to why declaring stuff as final doesn't make that much of a difference - the jitter will fold things that look like constants even if you don't declare them as final, and will only deoptimize if something happens that makes the optimization unsafe.

Sylink
Apr 17, 2004

Can anyone point me to some good tutorials or books that teach Java ground up without an IDE?

I'd like to compiler and write everything etc.

Grawl
Aug 28, 2008

Do the D.A.N.C.E
1234, fight!
Stick to the B.E.A.T
Get ready to ignite
You were such a P.Y.T
Catching all the lights
Just easy as A.B.C
That's how we make it right

Sylink posted:

Can anyone point me to some good tutorials or books that teach Java ground up without an IDE?

I'd like to compiler and write everything etc.

Head First's Java book is a good one.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Sylink posted:

Can anyone point me to some good tutorials or books that teach Java ground up without an IDE?

I'd like to compiler and write everything etc.

You probably want The JavaTM Virtual Machine Specification, Second Edition. That covers the output of the compiler -- Java bytecode instructions and their meaning to the JVM.

As for the input to the compiler, I'd go with The Java Language Specification, Third Edition. This goes in to a lot of detail about the grammar and lexical structure of the Java language.

Writing a Java compiler from the ground up is no easy task; godspeed :patriot:

Lysidas fucked around with this message at 00:14 on Jan 19, 2012

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
I think Sylink meant they want to compile everything (like, running javac), though I can see how "I'd like to compiler" can go either way

Sylink
Apr 17, 2004

Sorry my typing is awful. I meant I wanted to compile things from a command line after writing whatever in a text editor. Not using EZ mode IDE.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Referring to an IDE as "EZ mode" is ... odd.

By that I mean why wouldn't you use a tool designed to make things easier?

Pucklynn
Sep 8, 2010

chop chop chop

Jabor posted:

Referring to an IDE as "EZ mode" is ... odd.

By that I mean why wouldn't you use a tool designed to make things easier?

Every time I've been to a "for beginners" forum related to Java, people always fuss at the new kid who says he's got a shiny IDE that he's learning with and he'd better do it with a text editor and a command line and get off their lawn, goddamnit.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
"For beginners" forums are usually terrible places populated by a few guys who have some correct and some horribly incorrect ideas, and then a bunch of people who learned everything from those guys and have turned the place into an echo chamber.

In any case, Java's file structure is unnecessarily obtuse, and knowing all the fiddly details doesn't actually do anything to make you a better programmer.

Luminous
May 19, 2004

Girls
Games
Gains

Sylink posted:

Sorry my typing is awful. I meant I wanted to compile things from a command line after writing whatever in a text editor. Not using EZ mode IDE.

I think a better approach would be to tell us what you expect to gain by using just a command line, and then we could tell you whether or not what you expect is an accurate extrapolation of what will happen.

Pucklynn
Sep 8, 2010

chop chop chop

Luminous posted:

I think a better approach would be to tell us what you expect to gain by using just a command line, and then we could tell you whether or not what you expect is an accurate extrapolation of what will happen.

I'm not the one you're speaking to, specifically, but I have pretty much the same issue. My main grump with IDEs is that when I start a new project, it asks me about a million different setup options and populates files and bits of code that I just don't understand yet. Ideally I'd like to start with as minimalist a program as possible, to be sure I understand how each piece goes together. I feel like using the IDE skips over a lot of important basics of how a Java program is set up.

Sylink
Apr 17, 2004

Pucklynn posted:

I'm not the one you're speaking to, specifically, but I have pretty much the same issue. My main grump with IDEs is that when I start a new project, it asks me about a million different setup options and populates files and bits of code that I just don't understand yet. Ideally I'd like to start with as minimalist a program as possible, to be sure I understand how each piece goes together. I feel like using the IDE skips over a lot of important basics of how a Java program is set up.

Mostly this, I like to know the intents from the bottom level.

I don't have a personal problem with them, but I'd like to learn something as opposed to just typing in some settings while I have no idea what they are for.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
This is going to sound counter to what you guys want, but learn loving maven and be done with it. If you want to do anything with the Java ecosystem you're going to run into it, and it basically replaces all that setup that the IDE does, so I think it's worthwhile for beginners to learn and use it.

By placing all of your source files in the correct directories maven, will compile and generate a jar file containing the compiled sources. You can use that jar file directly from the command line and not have to deal with all the classpath bullshit. There is no benefit to know how to do that poo poo by hand, it's a huge waste of time and ultimately detracts from what you actually want to learn.

One of the main features of maven is its dependency resolution, but for your baby's first program you probably won't require any dependencies. As you start doing more complex things that aren't part of the standard api you'll want to use them and maven can help.

pigdog
Apr 23, 2004

by Smythe

Pucklynn posted:

I'm not the one you're speaking to, specifically, but I have pretty much the same issue. My main grump with IDEs is that when I start a new project, it asks me about a million different setup options and populates files and bits of code that I just don't understand yet. Ideally I'd like to start with as minimalist a program as possible, to be sure I understand how each piece goes together. I feel like using the IDE skips over a lot of important basics of how a Java program is set up.

Java IDEs don't necessarily do any of that. Yet if you choose to create a project structure, Ant build files and whatnot, then for projects larger than Hello World it's probably a good idea anyway. A good IDE checks syntax, integrity, imports etc on the fly and lets you fix them semi-automatically, saving you a lot of javac->edit->javac cycles. Going for commandline first is kinda similar to learning to write prose by insisting on using a pencil and paper, as opposed to word processor on a computer.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I mean if you're already familiar with a decent text editor and want to use that instead, then by all means set up a low-maintenance build system instead of using an IDE. (Don't try wrangle it manually though, that's still a bad idea).

But if your choice of editor doesn't give you anything that the built-in editor in an IDE gives you, just use an IDE because it seriously cuts out a lot of the meaningless busywork involved in writing Java.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm trying to write some basic server/client functionality using sockets, but I'm not able to get any communication to between the server and client to occur until the socket between them is closed.

http://pastebin.com/89T5tfkY is my server, and
http://pastebin.com/PC9pVTq6 is my client.

The client does print "Hello World", but only when the line sock.close() is reached at the server side, so the info transfer only happens at the point of disconnection, as far as I can see.

I need my client to receive information from the server and then be able to return requested information to the server, though. (You know, in general). Any pointers?

Doctor w-rw-rw-
Jun 24, 2008

Sedro posted:

No, Java can only close over final variables.

Personally, I try to make all fields/variables/parameters final. I'm curious, does this have any impact on performance?

The answer is: no...but yes in multithreaded environments.

In general it's a good idea to use final wherever possible. When I'm not on Android, I like making immutable objects for my models whenever I can. It's a useful design constraint so that rather than mutating a model object, possibly reading the in-memory representation for some updated data, and letting it be persisted at some random other time as well, I am forced to atomically update it in order for changes to be reflected. Doing this means (to me, anyway) that you can more easily design a proper abstraction for a multi-level cache because of stronger control over the workflow re: persisting poo poo.



MEAT TREAT posted:

This is going to sound counter to what you guys want, but learn loving maven and be done with it. If you want to do anything with the Java ecosystem you're going to run into it, and it basically replaces all that setup that the IDE does, so I think it's worthwhile for beginners to learn and use it.

By placing all of your source files in the correct directories maven, will compile and generate a jar file containing the compiled sources. You can use that jar file directly from the command line and not have to deal with all the classpath bullshit. There is no benefit to know how to do that poo poo by hand, it's a huge waste of time and ultimately detracts from what you actually want to learn.

One of the main features of maven is its dependency resolution, but for your baby's first program you probably won't require any dependencies. As you start doing more complex things that aren't part of the standard api you'll want to use them and maven can help.

Ah, yes. Maven. Sometimes an excellent tool. Its dependency resolution is hard to beat, but on the flip side it must be your entire universe should you decide to use it. M2Eclipse can sometimes play poorly with WDT+Eclipse (web), and M2Eclipse+ADT (Android) isn't something I've tested yet. On the other hand, I believe Ivy can access the same repositories as Maven can, without the build-system universe having to be ported over. Ant+Ivy is a common pairing (and it helps that the android tools provide a build.xml for you). While Maven can execute Ant tasks, it's also a reality that configuration can be arcane at times - sometimes simple things become incredibly complex, even when at the same time incredibly complex things become simple. I'm still very partial to Maven, but beware of its enterprisey nature.

pigdog posted:

Java IDEs don't necessarily do any of that. Yet if you choose to create a project structure, Ant build files and whatnot, then for projects larger than Hello World it's probably a good idea anyway. A good IDE checks syntax, integrity, imports etc on the fly and lets you fix them semi-automatically, saving you a lot of javac->edit->javac cycles. Going for commandline first is kinda similar to learning to write prose by insisting on using a pencil and paper, as opposed to word processor on a computer.

Pretty much.

  • Auto-import
  • Refactoring massive amounts of code
  • Auto-completion
  • Auto-stubbing of unimplemented methods
  • Code formatting
  • Incremental compilation as you write code
  • Automatic @Override annotation
  • Flagging deprecated methods
  • Displaying documentation inline with the autocompletion
  • Exception suggestions
  • Code path analysis (i.e. you forgot to return in this possible chain of if conditions in your method)

Java behaves as if it was practically designed to be written for you. I only write a small chunk of code; my IDE auto-completes the rest. A good Java programmer should be writing a low percentage of the actual text that comprises the code base, and spend all their typing and brainpower on business logic.

Doctor w-rw-rw- fucked around with this message at 20:14 on Jan 19, 2012

horse_ebookmarklet
Oct 6, 2003

can I play too?
What are the cool kids using these days for an MVC Framework? Struts 2 + Hibernate?
I've been playing around with the Spring + Hibernate and it seems to be pretty nice.

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried
Spring and Hibernate is pretty much the standard I think.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

NotHet posted:

What are the cool kids using these days for an MVC Framework? Struts 2 + Hibernate?
I've been playing around with the Spring + Hibernate and it seems to be pretty nice.

No one smart uses struts any more. Ugh.

I am a huge fan of Grails, which is basically lipstick on Spring + Hibernate with a bunch of other cool features.

Adbot
ADBOT LOVES YOU

Doctor w-rw-rw-
Jun 24, 2008

NotHet posted:

What are the cool kids using these days for an MVC Framework? Struts 2 + Hibernate?
I've been playing around with the Spring + Hibernate and it seems to be pretty nice.

Play framework is a really cool non-Servlet app framework. Klout and some other companies use it in production and its Scala support was good enough for Typesafe to anoint it officially as...something. I forgot. But its Java bindings are great, and I find it a lot of fun.

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