What is the difference between String[] and String... in Java?
How should I declare main() method in Java?
String[]
and String...
are the same thing internally, i. e., an array of Strings.
The difference is that when you use a varargs parameter (String...
) you can call the method like:
public void myMethod( String... foo ) {
// do something
// foo is an array (String[]) internally
System.out.println( foo[0] );
}
myMethod( "a", "b", "c" );
// OR
myMethod( new String[]{ "a", "b", "c" } );
// OR without passing any args
myMethod();
And when you declare the parameter as a String array you MUST call this way:
public void myMethod( String[] foo ) {
// do something
System.out.println( foo[0] );
}
// compilation error!!!
myMethod( "a", "b", "c" );
// compilation error too!!!
myMethod();
// now, just this works
myMethod( new String[]{ "a", "b", "c" } );
What's actually the difference between
String[]
andString
... if any?
The convention is to use String[]
as the main method parameter, but using String...
works too, since when you use varargs you can call the method in the same way you call a method with an array as parameter and the parameter itself will be an array inside the method body.
One important thing is that when you use a vararg, it needs to be the last parameter of the method and you can only have one vararg parameter.
You can read more about varargs here: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
What's the difference between [String] vs. [(String)]?
[String] is an array of strings, while [(String)] is an array of tuples which contain 1 string.
let arr1 = [("test")]
arr1[0].0 // contains "test"
let arr2 = ["test"]
arr2[0] // contains "test"
A more useful array of tuples might be something like:
let arr1: [(id: Int, name: String)] = [(12, "Fred"), (43, "Bob")]
arr1[0].name // contains "Fred"
Swift string vs. string! vs. string?
For your PancakeHouse
struct, name
is non-optional. That means that its name
property cannot be nil. The compiler will enforce a requirement that name
be initialized to a non-nil value anytime an instance of PancakeHouse
is initialized. It does this by requiring name
to be set in any and all initializers defined for PancakeHouse
.
For @IBOutlet
properties, this is not possible. When an Interface Builder file (XIB or Storyboard) is unarchived/loaded, the outlets defined in the IB file are set, but this always occurs after the objects therein have been initialized (e.g. during view loading). So there is necessarily a time after initialization but before the outlets have been set, and during this time, the outlets will be nil. (There's also the issue that the outlets may not be set in the IB file, and the compiler doesn't/can't check that.) This explains why @IBOutlet
properties must be optional.
The choice between an implicitly unwrapped optional (!
) and a regular optional (?
) for @IBOutlet
s is up to you. The arguments are essentially that using !
lets you treat the property as if it were non-optional and therefore never nil. If they are nil for some reason, that would generally be considered a programmer error (e.g. outlet is not connected, or you accessed it before view loading finished, etc.), and in those cases, failing by crashing during development will help you catch the bug faster. On the other hand, declaring them as regular optionals, requires any code that uses them to explicitly handle the case where they may not be set for some reason. Apple chose implicitly unwrapped as the default, but there are Swift programmers who for their own reasons, use regular optionals for @IBOutlet
properties.
What is the difference between types String and string?
Here is an example that shows the differences, which will help with the explanation.
var s1 = new String("Avoid newing things where possible");
var s2 = "A string, in TypeScript of type 'string'";
var s3: string;
String
is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2
in the example above creates a new string without the use of the new
keyword and without explicitly using the String
object.
string
is the TypeScript string type, which you can use to type variables, parameters and return values.
Additional notes...
Currently (Feb 2013) Both s1
and s2
are valid JavaScript. s3
is valid TypeScript.
Use of String
. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:
var arr = []; // not var arr = new Array();
var obj = {}; // not var obj = new Object();
If you really had a penchant for the string, you could use it in TypeScript in one of two ways...
var str: String = new String("Hello world"); // Uses the JavaScript String object
var str: string = String("Hello World"); // Uses the TypeScript string type
Difference between String interpolation and String concatenation
From a speed point of view, to differentiate concatenation (value1 + "-" + value2
) and interpolation ("\(value1)-\(value2)"
), results may depend on the number of operations done to obtain the final string.
My results on an iPhone 8 show that:
- if there is roughly < 30 substrings to attach together, then concatenation is faster
- if there is roughly > 30 substrings to attach together, then interpolation is faster
Thank you Sirens for figuring out that one wasn't always faster than the other!
Try it yourself (and don't forget to adapt the tested character set and iterations for your needs):
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.global(qos: .default).async {
ViewController.buildDataAndTest()
}
}
private static func buildDataAndTest(times: Int = 1_000) {
let characterSet = CharacterSet.alphanumerics
characterSet.cacheAllCharacters()
let data: [(String, String)] = (0 ..< times).map { _ in
(characterSet.randomString(length: 50), characterSet.randomString(length: 20))
}
_ = testCIA(data)
_ = testInterpol(data)
print("concatenation: " + String(resultConcatenation))
print("interpolation: \(resultInterpolation)")
}
/// concatenation in array
static var resultConcatenation: CFTimeInterval = 0
private static func testCIA(_ array: [(String, String)]) -> String {
var foo = ""
let start = CACurrentMediaTime()
for (a, b) in array {
foo = foo + " " + a + "+" + b
}
resultConcatenation = CACurrentMediaTime() - start
return foo
}
/// interpolation
static var resultInterpolation: CFTimeInterval = 0
private static func testInterpol(_ array: [(String, String)]) -> String {
var foo = ""
let start = CACurrentMediaTime()
for (a, b) in array {
foo = "\(foo) \(a)+\(b)"
}
resultInterpolation = CACurrentMediaTime() - start
return foo
}
}
extension CharacterSet {
static var cachedCharacters: [Character] = []
public func cacheAllCharacters() {
CharacterSet.cachedCharacters = characters()
}
/// extracting characters
/// https://stackoverflow.com/a/52133647/1033581
public func characters() -> [Character] {
return codePoints().compactMap { UnicodeScalar($0) }.map { Character($0) }
}
public func codePoints() -> [Int] {
var result: [Int] = []
var plane = 0
for (i, w) in bitmapRepresentation.enumerated() {
let k = i % 8193
if k == 8192 {
plane = Int(w) << 13
continue
}
let base = (plane + k) << 3
for j in 0 ..< 8 where w & 1 << j != 0 {
result.append(base + j)
}
}
return result
}
// http://stackoverflow.com/a/42895178/1033581
public func randomString(length: Int) -> String {
let charArray = CharacterSet.cachedCharacters
let charArrayCount = UInt32(charArray.count)
var randomString = ""
for _ in 0 ..< length {
randomString += String(charArray[Int(arc4random_uniform(charArrayCount))])
}
return randomString
}
}
What is the difference between String and string in C#?
string
is an alias in C# for System.String
.
So technically, there is no difference. It's like int
vs. System.Int32
.
As far as guidelines, it's generally recommended to use string
any time you're referring to an object.
e.g.
string place = "world";
Likewise, I think it's generally recommended to use String
if you need to refer specifically to the class.
e.g.
string greet = String.Format("Hello {0}!", place);
This is the style that Microsoft tends to use in their examples.
It appears that the guidance in this area may have changed, as StyleCop now enforces the use of the C# specific aliases.
What’s the difference between “{}” and “[]” while declaring a JavaScript array?
Nobody seems to be explaining the difference between an array and an object.
[]
is declaring an array.
{}
is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object"
to further show you that an array is an object.
The additional features consist of a magic .length
property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push()
, .pop()
, .slice()
, .splice()
, etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo
syntax or via the array-like syntax x["foo"]
. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar]
and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo
syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0
and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort()
or to add or remove things from the list.
What's the difference between String and String[]?
String is -> a series of characters in your code that is enclosed in double quotes.
More details a bout String
String[] -> An array is a container object that holds a fixed number of values of a Strings.
More about Arrays
Related Topics
Cannot Convert Value of Type 'X' to Expected Argument Type 'X'
Which Optimization Level Should I Choose for Release
A Concise Way to Not Execute a Loop Now That C-Style for Loops Are Going to Be Removed from Swift 3
Performseguewithidentifier Not Working If Called from Viewdidload
Cmlogitem Timestamp: Why So Complicated
Count Number of Instances of a Class Swift
How to Cast Sockaddr_In to Sockaddr in Swift
Sknode Subclass Generates Error: Cannot Invoke Initializer for Type "X" with No Arguments
How to Get The Count of a Type Conforming to 'sequence'
Why I Can Not Use Setvalue for Dictionary
How to Define a Variable in a Swift If Statement
Filtering Realm Objects with Swift
Keyboard Height Change Observer Swift
How to Get The Push Notifications Displayed in The Notification Center
Swift Nwlistener Listen, Cancel, and Relisten Successfully
Swift 2 Mkmapviewdelegate Rendererforoverlay Compiler Warning
Add UIview (From Xib) with Transparency to Scenekit
In Swift 5, What Is a Way to Compare Pointers to Two Closures