Does hash function djb2 have java version? - java

I saw that java can't handle unsigned long...
If yes, can any one post the code? Thanks.

Are you going to be interoperating with languages featuring unsigned types? If not you can probably just use the standard java long without a problem. It will probably overflow anyways (as per the discussion here djb2 Hash Function) but that's not a problem.
Here's a PermissionSet class in the wild using this implementation. Don't forget that a hashCode in Java needs to return an integer anyways, so the lack of an unsigned long should not make a difference - there will just be fewer possible values that the function takes on.

Related

How can everything be an object? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
In Java for example there is the primitive data type "int" which represents a 32 Bit value and there is "Integer" which is just a class with a single "int" property (and some methods of course). That means that a Java "Integer" class still uses primitives behind the scenes. And that's the reason Java is not a pure object oriented programming language.
Where could a value be stored if there where no primitives? For example I imagine this pseudo class:
class Integer
{
private Integer i = 12;
public Integer getInteger
{
return this.Integer;
}
}
This would be recursive.
How can a programming language be implemented without primitives?
I appreciate any help solving my confusion.
Behind the scene always will be primitives because it just a bits in memory. But some languages hide primitives that You can work only with objects. Java allows You to work both with objects and primitives.
If you mean by primitives value types, then yes you can live without them as a user and use Integer instead of int and pay for the overhead of heap allocation and GC. But this doesn't come for free and you have to pay the cost. Primitives like 32-bit/64-bit integers and IEEE-754 floating points will always be faster because there is a hardware support for them.
From a compiler writer point of view you have to use what the machine supports to make things work.
LISP is a very simple functional language. The basic LISP did not have a primitive int and one solution to integers was to have successor of successor of successor of zero for 3.
This actually had some advantages, integers being open ended, no overflow so operations really commutative, associative, and so on. Some nice optimizations possible. And of course succ(succ(succ(zero))) could be encoded in a more tuple like way (probably better not in LISP).
In a later, normal, LISP '3' would be an atom, 123 would be such an atom, with math operators.
Then there are symbol manipulating languages (SNOBOL) that could do math on numerical strings ['4', '0'] * ['3'].
So names are objects (atoms) like a char 'a' or int 42.
It might help to show you the analogous code in a language that takes the "everything is an object" design principle much more seriously than Java does. Namely, Smalltalk. Imagine what it would be like if Java had only int, not Integer, but everything you used to need to use Integer for was possible with int. That's Smalltalk.
This is an excerpt of the code defining the SmallInteger class in Squeak 5.0:
Integer immediateSubclass: #SmallInteger
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Kernel-Numbers'!
!SmallInteger commentStamp: 'eem 11/20/2014 08:41' prior: 0!
My instances are at least 31-bit numbers, stored in twos complement
form. The allowable range in 32-bits is approximately +- 10^9
(+- 1billion). In 64-bits my instances are 61-bit numbers,
stored in twos complement form. The allowable range is
approximately +- 10^18 (+- 1 quintillion). The actual
values are computed at start-up. See SmallInteger class startUp:,
minVal, maxVal.!
!SmallInteger methodsFor: 'arithmetic' stamp: 'di 2/1/1999 21:31'!
+ aNumber
"Primitive. Add the receiver to the argument and answer with the result
if it is a SmallInteger. Fail if the argument or the result is not a
SmallInteger.
Essential, No Lookup. See Object documentation whatIsAPrimitive."
<primitive: 1>
^ super + aNumber! !
!SmallInteger class methodsFor: 'instance creation' stamp: 'tk 4/20/1999 14:17'!
basicNew
self error: 'SmallIntegers can only be created by performing arithmetic'! !
Don't sweat the fine details of syntax or semantics. What you should get out of this is: SmallInteger is defined as an object class just like everything else in the language, and arithmetic operations are methods just like every other piece of code in the language. But it's a little odd. It has no instance variables, you can only create instances by performing arithmetic, and most of the methods look like they're being defined circularly.
"Under the hood", the implementation maps arithmetic to the appropriate machine instructions (the <primitive: 1> thing is a hint to the implementation about that) and stores SmallIntegers as nothing more than the integer itself. The restricted range, relative to the hardware, is because a couple of bits are reserved to mark memory words as integers, rather than pointers to objects ("tagged pointers").
Without being able to eventually access real data, (eg. primitives or actual bits) (directly or indirectly) on a machine, it is no longer a programming language, it is an Interface Description Language.
(I'll rephrase the question to what I believe you're asking. If you think I've got it wrong, feel free to comment.)
How can a type system that's based on composition and inheritance define any useful type, if there are no intrinsic types to start from? Unless the language implementation knows about at least one intrinsic type to start from, any defined types would be doomed to be either recursive or empty. Is this inevitable?
Yes, in every C-family language that I know of, this is pretty much inevitable.
If every type is composed of other types then, at the very least, you need to have an intrinsic type to build upon - for example, an intrinsic type that represents a bit, in order to construct the byte type out of it through composition, then the word type, then various integer types, and so on. Then you'd need to define the operations that can be performed on these types, by manipulating the bits that make up their internal representation.
And even though all you need is one intrinsic type to build upon, it would likely be terribly inefficient - you don't want to waste space or CPU cycles and you do want to take advantage of the various storage locations and instructions that your target architecture offers, including FP registers and other stuff.
Thus, a good compromise between performance and "purity" is to offer in the language some intrinsic types that are likely to be recognizable by modern CPUs (like int32, int64, float, double, etc) and build the rest of the type system upon them. In Java, they decided to call these intrinsic types primitives and make them separate from classes.
Eventually everything comes back to bits in memory and instructions to the computer. The difference between assembler, compiled, procedural, object oriented, and all the other things is how much abstraction there is between you and the bits and how much benefit (or cost) you get from that abstraction.

JNI: equivalent of uint *vboIds in Java

I'm developing a java application that uses some jni calls.
I have on C code the following variable:
GLuint *vboIds;
I want to pass this variable from Java to C, but I don't know how to declare it in Java.
GLuint is equivalent an unsigned int.
So, I think this is the equivalent declaration in Java:
int[] vboIds;
What do you think?
Thanks
You don't say explicitly whether it is meant to be a pointer to a single value or an array, but I'd guess it's probably an array from the naming and what you are thinking of doing with the mapping (there should also be a parameter somewhere that specifies the length of the array; those both map to the same argument on the Java side as Java's arrays know their own lengths). You're probably right to use an int as that's generally the same size as a C int – not that that's a guarantee, not at all, but hardly any machine architectures are different from that these days – but you'll need to watch out for the fact that Java's numeric types are all signed. That's mostly not a problem provided you're a bit careful with arithmetic (other than addition, subtraction and left-shift, which work obviously) and comparisons.

Java for Clojure users

I've been using Lisp on and off, and I'm catching up with clojure.
The good thing about clojure is that I can use all the java functions naturally, and the bad thing about clojure is also that I have to know java function naturally.
For example, I had to spend some time (googling) to find square function in Java (Math/sqrt in clojure notation).
Could you recommend me some good information resource for Java functions (libraries) for clojure users that are not so familiar with Java?
It can be anything - good books, webpages, forums or whatever.
I had similar problems when I first started using Clojure. I had done some Java development years ago, but was still pretty unfamiliar with the libraries out there.
Intro
I find the easiest way to use Java is to not really use it. I think a book would be a little bit much to just get started using Java from Clojure. There isn't that much you really need to know, unless you really start getting down into the JVM/Java libraries. Let me explain.
Spend more time learning how to use Clojure inside and out, and become familiar with Clojure-Contrib. For instance, sqrt is in generic.math-functions in clojure.contrib.
Many of the things you'll need are in fact already in Clojure–but still plenty are not.
Become familiar with calling conventions and syntactic sugar in Clojure for using Java. e.g. Math/sqrt, as per your example, is calling the static method (which just a function, basically) sqrt from the class Math.
Anyway, here's a guide that should help you get started if you find yourself really needing to use Java. I'm going to assume you've done some imperative OO programming, but not much else. And even if you haven't, you should be okay.
Isaac's Clojurist's Guide to Java
Classes
A class is a bundle of methods (functions which act on the class) that
can also be a data type: e.g. to create a new class of the type Double : (Double. 1.2) which initializes the class Double (the period is the syntactic sugar for calling the class constructor methods, which initialize the class with the values you provide) with the value 1.2.
Now, look at the Double class in the Java 6 API:
Double
public Double(double value)
Constructs a newly allocated Double object that represents the
primitive double argument.
Parameters:
value - the value to be represented by the Double.
So you can see what happened there. You "built" a new Double with value 1.2, which is a double. A little confusing there, but really a Double is a class that represents a Double and can do things relating to doubles.
Static Methods
For instance, to parse a Double value out of a string, we can use the static method (meaning we don't need a particular instance of Double, we can just call it like we called sqrt) parseDouble(String s):
(Double/parseDouble "1.2") => 1.2
Not to tricky there.
Nonstatic Methods
Say we want to use a Java class that we initialized to something. Not too difficult:
(-> (String. "Hey there") ;; make a new String object
(.toUpperCase)) ;; pass it to .toUpperCase (look up -> to see what it does)
;; toUpperCase is a non-static method
=> "HEY THERE"
So now we've used a method which is not static, and which requires a real, live String object to deal with. Let's look at how the docs say it works:
toUpperCase
public String toUpperCase()
Converts all of the characters in this String to upper case using
the rules of the default locale. This method is equivalent to
toUpperCase(Locale.getDefault()).
Returns:
the String, converted to uppercase.
So here we have a method which returns a string (as shown by the "String" after the public in the definition, and takes no parameters. But wait! It does take a parameter. In Python, it'd be the implicit parameter self: this is called this in Java.
We could also use the method like this: (.toUpper (String. "Hey there")) and get the same result.
More on Methods
Since you deal with mutable data and classes in Java, you need to be able to apply functions to Classes (instances of Classes, really) and not expect a return value.
For instance, say we're dealing with a JFrame from the javax.swing library. We might need to do a number of things to it, not with it (you generally operate with values, not on them in functional languages). We can, like this:
(doto (JFrame. "My Frame!");; clever name
(.setContentPane ... here we'd add a JPanel or something to the JFrame)
(.pack) ;; this simply arranges the stuff in the frame–don't worry about it
(.setVisibleTrue)) ;; this makes the Frame visible
doto just passes its first argument to all the other functions you supply it, and passes it as the first argument to them. So here we're just doing a lot of things to the JFrame that don't return anything in particular. All these methods are listed as methods of the JFrame in the documentation (or its superclasses… don't worry about those yet).
Wrapping up
This should prepare you for now exploring the JavaDocs yourself. Here you'll find everything that is available to you in a standard Java 1.6 install. There will be new concepts, but a quick Google search should answer most of your questions, and you can always come back here with specific ones.
Be sure to look into the other important Clojure functions like proxy and reify as well as extend-type and its friends. I don't often use them, but when I need to, they can be invaluable. I still am understanding them myself, in fact.
There's a ton out there, but it's mostly a problem of volume rather than complexity. It's not a bad problem to have.
Additional reading:
Static or Nonstatic? ;; a guide to statis vs. nonstatic methods
The Java Class Library ;; an overview of what's out there, with a nice picture
The JavaDocs ;; linked above
Clojure Java Interop Docs ;; from the Clojure website
Best Java Books ;; as per clartaq's answer
Really, any good Java book can get you started. See for example the answer to the question about the
best Java book people have read so far. There are lots of good sources there.
Once you have a little Java under you belt, using it is all just a matter of simple Clojure syntax.
Mastering the content of the voluminous Java libraries is a much bigger task than figuring out how to use them in Clojure.
My first question would be: what do you exactly need? There are many Java libraries out there. Or do you just need the standard libraries? In that case the answer given by dbyrne should be enough.
Keep in mind that in general you are better of using the Clojure data structures like sequences instead of the Java equivalents.
Start with the Sun (now Oracle) Java Tutorials: http://download.oracle.com/javase/tutorial/index.html
Then dive into the Java 6 API docs:
http://download-llnw.oracle.com/javase/6/docs/
Then ask questions on #clojure IRC or the mailing list, and read blogs.
For a deep dive into Java the language, I recommend Bruce Eckel's free Thinking in Java:
http://www.mindview.net/Books/TIJ/
I think the plain old Java 6
API Specification should be pretty much all you need.

BigInteger or not BigInteger?

In Java, most of the primitive types are signed (one bit is used to represent the +/-), and therefore when I exceed the limits of the type, I can get unexpected results, like negative numbers.
Is there any better solution than using BigInteger for this, since BigInteger has performance issues and you need to use the class methods for basic arithmetic instead of the language operators (ruins readability)?
No, there is not a better solution. If you are working with values that cannot fit into a long or a double then you will need to use a reference type like BigInteger, and Java does not support operator overloading.
Technically, I suppose you could have some mapping between signed and unsigned values, but if your goal is clean and simple code then this is not at all the way to go.
Scala is really the solution here. In that language "operators" are really just in-fixed methods, and can be defined for arbitrary classes. In fact in your case they already are in the standard library. So you can have the power of special number representations but the clean syntax of Java primitive types.
Scala is battle-hardened and will be fully interoperable with your Java code.
The only way for still having beautiful buisiness logic is using a script language, which you compile to java classes. Internally you can use BigIntegers then.

What is the right way to change an Integer in a Vector in Java (j2me)

As a follow up to my question about j2me dynamic arrays,
I'm now trying to figure out a way to change the values of the Integers in my Vector.
Say I have a Vector v, and Array arr, and ints x, y and i;
In c++ I could do:
v[arr[x][y]] += i;
In j2me the best way I found so far to do the same is:
v.setElementAt(new Integer(((Integer)(v.elementAt(arr[x][y]))).intValue()+i), arr[x][y]);
Is this really the best way to do it j2me?
If it is, what went wrong here? Java is supposed to make me "do less work" and "do things for me" yet I find myself again and again doing extra work for it. Is something wrong with me, or is it some problem with Java?
Edit: I'm using the J2me SDK 3.0 which looks like it is Java 1.3 so no fancy generics and auto boxing and all that stuff.
I'm afraid that's how it is in ME, although I'd split it to avoid that hairy oneliner:
Integer val = (Integer)v.elementAt(arr[x][y]);
int newVal = val.intValue() + i;
v.setElementAt(new Integer(newVal), arr[x][y]);
Stuff got a lot better with autoboxing and generics, but they came in Java 5 and J2ME is basically a stripped version of Java 1.3 unless I've been misinformed. Here's how it looks in Java 5+:
v.setElementAt(arr[x][y], v.get(arr[x][y]) + i);
Still more verbose than C++, but at least without the casting. I understand there was reluctance to add generics and such to Java as it might be "too hard" for the average programmer to understand [Citation needed]. And so we ended up with unreadable code until .Net got generics and Sun jumped on the bandwagon.
Anywho, I agree the collections framework was a pain to use before generics/boxing, but I hope at least you'll enjoy not having to debug broken pointers and corrupted memory.
Java SE has had some changes to the language (Generics) that would make this code a bit simpler, for ME I'd guess you are out of luck.
I would go for the suggested solution of creating your own class that wraps a plain array (and allocates a bigger one when needed) that was given as an answer to your previous question.
You have two things here that are conspiring to bloat the code: Lack of a typesafe collection, and an immutable int wrapper.
One solution would be to use a typesafe collection. GNU Trove has TIntArrayList for this:
v.set(arr[x][y], v.get(arr[x][y]) + i);
Alternatively, you can use a mutable class like org.jboss.util.MuInteger:
((MuInteger)v.elementAt(arr[x][y])).add(i);
Or, as a dirty hack, arrays of length 1:
((int[])v.elementAt(arr[x][y]))[0] += i;
If you can combine both (would definitely require you to write a a custom collection class, in the absence of Generics):
v.get(arr[x][y]).add(i);
I don't see the reason why you wouldn't do it the same way as you do in C++. OK, you have to implement the dynamically scaling array container yourself but if you do, you get rid of the Integer issue where Java actually creates a new Object of type Integer instead of int primitive type.
Your original question has a nice example of a dynamic int primitive type array as an answer, go check it out again.
Vector<Integer> v = new Vector<Integer>();
v.setElementAt( arr[x][y], arr[x][y] );
EDIT: While answering this question, I did not know that J2ME does not support Generics. Thanks to SO for teaching me that :-)
EDIT 2: My solution is wrong since J2ME does not support Generics.
If you have used Generics (JDK 1.5 onwards), you could do it simpler!
If I assume the declaration to be thus,
Vector<Integer> v = new Vector<Integer>();
then
v.setElementAt(new Integer(((Integer)(v.elementAt(arr[x][y]))).intValue()+i), arr[x][y]);
becomes
v.setElementAt(new Integer(v.elementAt(arr[x][y]).intValue()+i), arr[x][y]);

Categories

Resources